servlet中的doGet方法

时间:2013-09-10 09:35:03

标签: servlets

这是我试图实现的东西。我已经写了doGet方法,我现在如何映射doPost方法?

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String forward="";
    String act = request.getParameter("act");
    if (act != null && !act.equalsIgnoreCase("null") &&
           act.equalsIgnoreCase("login")) {
       forward= "/Login.jsp";
    } else if (act!= null && !act.equalsIgnoreCase("null") &&
            act.equalsIgnoreCase("register")) {
        forward = LIST_USER;
        request.setAttribute("users", dao.getAllUsers());
    } else {
        forward = "/Login.jsp";
    }

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

3 个答案:

答案 0 :(得分:0)

如果你想像GET一样处理POST,你可以做到

protected void doPost((HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request,response);
}

答案 1 :(得分:0)

如果你想以类似的方式处理POST和GET,那么你可以添加第三种方法

doSomething(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

并从两个

调用它
  

doGet and do Post

例如

doSomething(request,response);

答案 2 :(得分:0)

这是Netbeans IDE生成的默认代码。

将代码保存在常用方法中并将其映射到调用方法。

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
} 

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    processRequest(request, response);
} 

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    processRequest(request, response);
}