1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| @WebServlet("*.do") public class UserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8");
String servletPath = request.getServletPath(); int start = servletPath.lastIndexOf("/") + 1; int end = servletPath.lastIndexOf(".do"); String methodName = servletPath.substring(start, end);
try { Method method = getClass().getDeclaredMethod( methodName, HttpServletRequest.class, HttpServletResponse.class ); method.invoke(this, request, response); } catch (NoSuchMethodException e) { response.getWriter().write("不支持的操作:" + methodName); } catch (Exception e) { e.printStackTrace(); response.getWriter().write("操作失败:" + e.getMessage()); } }
private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("users", userService.findAll()); request.getRequestDispatcher("/user/list.jsp").forward(request, response); }
private void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/user/add.jsp").forward(request, response); }
private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); userService.save(new User(username)); response.sendRedirect(request.getContextPath() + "/user/list.do"); }
private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int id = Integer.parseInt(request.getParameter("id")); userService.delete(id); response.sendRedirect(request.getContextPath() + "/user/list.do"); } }
|