前提
![]()
代码
1 @WebServlet("/ajaxTest1/*")
2 public class BaseServlet1 extends HttpServlet {
3
4 @Override
5 protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
6 //1.分割获得方法名
7 String requestURI = req.getRequestURI();
8 System.out.println("requestURI = " + requestURI);//打印结果:requestURI = /day17/ajaxTest1/add
9 String meThodName = requestURI.substring(requestURI.lastIndexOf("/") + 1);
10 System.out.println("substring = " + meThodName);//打印结果:substring = add
11 //2.(反射)通过类对象获得该类所有方法
12 try {
13 Method declaredMethod = this.getClass().getDeclaredMethod(meThodName, HttpServletRequest.class, HttpServletResponse.class);
14 //3.执行方法
15 declaredMethod.invoke(this,req,resp);
16 } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
17 //4.使用404常量
18 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
19 }
20
21
22 }
23
24 public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
25
26 System.out.println("add 执行了");
27 }
28 }
29 /*===============================================================
30 * 启动Tomcat => 浏览器输入 => http://localhost/day17/ajaxTest1/add
31 * ==============================================================*/