Servlet优化

通过重写父类的service方法再用invoke调用子类的手段实现,是一个非常好的反射案例!!!!!!!

image.png

原因在于servlet太多不方便

问题在于HttpServlet用不了了,得自己想办法

uri是短路径/url是长路径

此处新建了一个项目BaseServlet

  1. package top.wjysb.servlet;
  2. import javax.servlet.ServletException;
  3. import javax.servlet.http.HttpServlet;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. import java.io.IOException;
  7. import java.lang.reflect.InvocationTargetException;
  8. import java.lang.reflect.Method;
  9. public class BaseServlet extends HttpServlet {
  10. @Override
  11. protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  12. String requestURI = req.getRequestURI();
  13. int index = requestURI.lastIndexOf("/");
  14. String methodName = requestURI.substring(index + 1);
  15. Class<? extends BaseServlet> aClass = this.getClass();
  16. try {
  17. Method method = aClass.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
  18. method.invoke(this, req, resp);
  19. } catch (NoSuchMethodException e) {
  20. e.printStackTrace();
  21. } catch (IllegalAccessException e) {
  22. e.printStackTrace();
  23. } catch (InvocationTargetException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. }
  1. package top.wjysb.servlet;
  2. import javax.servlet.ServletException;
  3. import javax.servlet.annotation.WebServlet;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. import java.io.IOException;
  7. @WebServlet("/User/*")
  8. public class UserServlet extends BaseServlet {
  9. public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  10. System.out.println("select all method");
  11. }
  12. public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  13. System.out.println("add method");
  14. }
  15. }

运行进入
http://localhost:8080/BaseServlet_war/User/add
http://localhost:8080/BaseServlet_war/User/selectAll
能够看到
image.png
就代表没问题了

相关知识https://blog.csdn.net/weixin_40512519/article/details/80790445

此处修改理论上可以把所有的servlet写到一起,但是可能存在其他问题
private的service只用写一个了,根据service一一对应servlet比较合理

分页查询(暂时不用servlet优化写了

image.png

此处重点在于分页需要一个泛型实体,能够很好的应对各种类型数据

  1. package top.wjysb.pojo;
  2. import java.util.List;
  3. public class Page<T> {
  4. private int totalCount;
  5. private List<T> rows;
  6. public int getTotalCount() {
  7. return totalCount;
  8. }
  9. public void setTotalCount(int totalCount) {
  10. this.totalCount = totalCount;
  11. }
  12. public List<T> getRows() {
  13. return rows;
  14. }
  15. public void setRows(List<T> rows) {
  16. this.rows = rows;
  17. }
  18. }

image.png
image.png

最后的tip

image.png

箭头函数可以不用另写this了

记得like的时候给上两个%%,不用怕空字符串,加%不会有问题

附上完整代码
链接:https://pan.baidu.com/s/1hciltgU6EBiKZ12UFekFog?pwd=ja26
提取码:ja26
—来自百度网盘超级会员V6的分享