BaseServlet抽取
优化Servelet,减少Servlet数量,现在是一个功能一个Servlet,将其优化为一个模块一个Servlet相当于在数据库中一张表对应一个Servlet,现在Servlet中提供不同的方法,完成用户的请求,
图解:
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// System.out.println("BaseServlet的service的方法被执行了...");
// 完成方法分发
// 获取请求路径
String uri = req.getRequestURI();
System.out.println("请求的路径"+uri);
// 获取方法名称
String name = uri.substring(uri.lastIndexOf("/") + 1);
System.out.println("方法名称"+name);
// 获取方法对象Method
System.out.println(this);
try {
// 忽略访问权限符
Method method = this.getClass().getDeclaredMethod(name, HttpServletRequest.class, HttpServletResponse.class);
// 暴力反射
// method.setAccessible(true);
// 执行方法
method.invoke(this,req,resp);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
@WebServlet("/user/*")
public class UserServlet extends BaseServlet{
public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("user的add方法...");
}
public void find(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("user的find方法...");
}
}
标签:BaseServlet,抽取,req,System,println,Servlet,out From: https://www.cnblogs.com/ssr1/p/16629997.html