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


做一個Login Demo的時候,寫了如下代碼:


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,包括如下部分:

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

請注意在做doPost(..)的時候我這里調用了super.doPost(..),而super.doPost(..)做了什么呢?

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(..),程序正常運行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM