【问题标题】:doGet method in a servletservlet 中的 doGet 方法
【发布时间】:2013-09-10 09:35:03
【问题描述】:

这是我试图实现的东西。我已经编写了 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);
} 

【问题讨论】:

  • 我不明白你在问什么。 “映射 doPost 方法”是什么意思?另外,请正确缩进您的代码。

标签: servlets


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    并从两者中调用它

    doGet 和做 Post

    例如

    doSomething(request,response);
    

    【讨论】:

      【解决方案3】:

      这是 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);
      }
      

      【讨论】:

        猜你喜欢
        • 2011-08-18
        • 1970-01-01
        • 2012-02-27
        • 1970-01-01
        • 2012-07-16
        • 2012-11-12
        • 2015-06-02
        • 1970-01-01
        • 2012-01-31
        相关资源
        最近更新 更多