Servlet优化
通过重写父类的service方法再用invoke调用子类的手段实现,是一个非常好的反射案例!!!!!!!
原因在于servlet太多不方便
uri是短路径/url是长路径
此处新建了一个项目BaseServlet
package top.wjysb.servlet;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class BaseServlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String requestURI = req.getRequestURI();int index = requestURI.lastIndexOf("/");String methodName = requestURI.substring(index + 1);Class<? extends BaseServlet> aClass = this.getClass();try {Method method = aClass.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);method.invoke(this, req, resp);} catch (NoSuchMethodException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}}}
package top.wjysb.servlet;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@WebServlet("/User/*")public class UserServlet extends BaseServlet {public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("select all method");}public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("add method");}}
运行进入
http://localhost:8080/BaseServlet_war/User/add
http://localhost:8080/BaseServlet_war/User/selectAll
能够看到
就代表没问题了
相关知识https://blog.csdn.net/weixin_40512519/article/details/80790445
此处修改理论上可以把所有的servlet写到一起,但是可能存在其他问题
private的service只用写一个了,根据service一一对应servlet比较合理
分页查询(暂时不用servlet优化写了
此处重点在于分页需要一个泛型实体,能够很好的应对各种类型数据
package top.wjysb.pojo;import java.util.List;public class Page<T> {private int totalCount;private List<T> rows;public int getTotalCount() {return totalCount;}public void setTotalCount(int totalCount) {this.totalCount = totalCount;}public List<T> getRows() {return rows;}public void setRows(List<T> rows) {this.rows = rows;}}
最后的tip
箭头函数可以不用另写this了
记得like的时候给上两个%%,不用怕空字符串,加%不会有问题
附上完整代码
链接:https://pan.baidu.com/s/1hciltgU6EBiKZ12UFekFog?pwd=ja26
提取码:ja26
—来自百度网盘超级会员V6的分享


