一个servlet处理多个功能

servlet中:

 1 String servletPath = request.getServletPath();
 2         String methodName = servletPath.substring(1);
 3         methodName = methodName.substring(0, methodName.length() - 3);
 4         Method method;
 5         try {
 6             method = getClass().getDeclaredMethod(methodName,
 7                     HttpServletRequest.class, HttpServletResponse.class);
 8             method.invoke(this, request,response);
 9         } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
10             // TODO Auto-generated catch block
11             e.printStackTrace();
12         }
13         
14     }
15 
16     private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
17         
18         System.out.println("update");
19     }
20     private void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
21         List<User> list = dao.getAll();
22         request.setAttribute("list", list);
23         request.getRequestDispatcher("/index.jsp").forward(request, response);;
24         System.out.println("query");
25     }
26     private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
27         
28         System.out.println("delete");
29     }private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
30         
31         System.out.println("add");
32     }

web.xml文件:

1  <servlet-mapping>
2     <servlet-name>UserServlet</servlet-name>
3     <url-pattern>*.do</url-pattern>
4   </servlet-mapping>

jsp:

<a href="add.do">add</a>
<a href="delete.do">delete</a>
<a href="query.do">query</a>
<a href="update.do">update</a>
原文地址:https://www.cnblogs.com/xing-12/p/6255782.html