protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String forward="";
    String action = request.getParameter("action");

    if (action.equalsIgnoreCase("delete")){
        int userId = Integer.parseInt(request.getParameter("userId"));
        dao.deleteUser(userId);
        forward = LIST_USER;
        request.setAttribute("users", dao.getAllUsers());
    } else if (action.equalsIgnoreCase("edit")){
        forward = INSERT_OR_EDIT;
        int userId = Integer.parseInt(request.getParameter("userId"));
        User user = dao.getUserById(userId);
        request.setAttribute("user", user);
    } else if (action.equalsIgnoreCase("listUser")){
        forward = LIST_USER;
        request.setAttribute("users", dao.getAllUsers());
    } else {
        forward = INSERT_OR_EDIT;
    }

    RequestDispatcher view = request.getRequestDispatcher(forward);
    view.forward(request, response);
}}

最佳答案

request.getParameter("action");在此处为空

所以用

 if (action!=null && action.equalsIgnoreCase("delete")){
       int userId = Integer.parseInt(request.getParameter("userId"));
    dao.deleteUser(userId);
    forward = LIST_USER;
    request.setAttribute("users", dao.getAllUsers());
} else if (action!=null && action.equalsIgnoreCase("edit")){
    forward = INSERT_OR_EDIT;
    int userId = Integer.parseInt(request.getParameter("userId"));
    User user = dao.getUserById(userId);
    request.setAttribute("user", user);
} else if (action!=null && action.equalsIgnoreCase("listUser")){
    forward = LIST_USER;
    request.setAttribute("users", dao.getAllUsers());
} else {
    forward = INSERT_OR_EDIT;
}

10-06 06:08