2
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);
}}
4

4 回答 4

23

改成,可以把常量部分作为主对象,然后检查变量部分是否相等

"delete".equalsIgnoreCase(action)
于 2013-05-23T11:25:42.843 回答
2

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;
}
于 2013-05-23T11:25:43.947 回答
1

虽然我更喜欢 Arun P Johny 的解决方案,但也许这个辅助方法也很有用:

public String getParameter(HttpServletRequest request, String parameterName, String defaultvalue) {
    String result = request.getParameter(parameterName);

    return (result != null) ? result : defaultValue;
}

然后打电话

String action = getParameter(request, "action", "");
于 2013-05-23T11:39:36.633 回答
-1

尝试使用

 String action = request.getParameter("action")+"";

所以所有其他检查都不会给出 NPE。

于 2013-05-23T11:27:14.457 回答