zoukankan      html  css  js  c++  java
  • 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(..),程序正常运行。

  • 相关阅读:
    条件变量:为什么要与互斥锁配套使用?为什么要使用while来避免虚假唤醒?
    【转】高性能IO之Reactor模式
    LeetCode127:单词接龙
    CF1245F: Daniel and Spring Cleaning
    权值线段树学习笔记
    luogu_4317: 花神的数论题
    luogu_2605: 基站选址
    入门平衡树: Treap
    CF1244C: The Football Season
    luogu_1156: 垃圾陷阱
  • 原文地址:https://www.cnblogs.com/lyxcode/p/7571363.html
Copyright © 2011-2022 走看看