
我们先定义一个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就解决了该问题



















