javaweb 使用element + vue 完善项目 servlet 优化

我们先定义一个BaseServlet,继承HttpServlet 重写Service方法 (因为HttpServlet就是在Service方法里做的通过请求方式进行方法分发,我们就重写改成通过请求路径分发)

根据资源路径进行方法分发,利用反射得到调用者的class字节码文件并调用对应方法

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取请求的路径
        String uri =req.getRequestURI(); //  /brand-case/brand/selectAll
        //2.获取最后一段路径  根据最后一个“/”的索引+1截取后面的字符串
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);

        //3 执行方法
        // 获取BrandServlet 或者UserServlet的字节码对象class  谁调用,谁就是this
        Class<? extends BaseServlet> cls = this.getClass();
        //获取方法Method对象
        try {
            Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }


    }
}

其他的像 BrandServlet  或者 UserServlet 只需要继承BaseServlet并写各自的方法就可以了

(需要在方法传递request跟response参数)

@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet {

    public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        System.out.println("Brand 的 selectAll 方法");
    }
    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        System.out.println("Brand的add方法");
    }
}

今天在写selectByUser方法的时候,遇到了axios里面代码段无法被执行的情况

if (resp.data == "false"){
    _this.$message({
        message:"未查询到您想要的数据",
        type:"error"
    })
}

因为在js中 false代表的是boolean类型的

我们传入的false是字符串就会导致if失效

所以直接换成了_false就解决了该问题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值