[Java][Servlet] Cannot call sendRedirect() after the response has been committed

作一個Login Demo的時候,寫了以下代碼:java

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    super.doPost(request, response);
    
    String userName = request.getParameter("userName");
    String password = request.getParameter("password");

    if (userName.equals("test")) {
        response.sendRedirect(request.getContextPath() + "/success/success.jsp");
    } else {
        response.sendRedirect(request.getContextPath() + "/error/login-failed.jsp");
    }
}

運行程序時報錯了Cannot call sendRedirect() after the response has been committed,意思已經很明確了,就是說不能在一個response作了提交以後再重定向,也就是說再重定向以前不要去改變response,包括以下部分:cookie

  • 修改response中參數的值,cookie,session 等
  • 重定向

請注意在作doPost(..)的時候我這裏調用了super.doPost(..),而super.doPost(..)作了什麼呢?session

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {

    String protocol = req.getProtocol();
    String msg = lStrings.getString("http.method_post_not_supported");
    if (protocol.endsWith("1.1")) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
    } else {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
    }
}

response被修改了,咱們註釋掉super.doPost(..),程序正常運行。jsp

相關文章
相關標籤/搜索