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

  • 相关阅读:
    python+selenium截图
    selenium鼠标事件
    python位置参数、默认参数、关键字参数、可变参数的区别
    元素定位
    selenium下拉框选择
    mysql计算日期的函数
    python列表操作
    requests库及请求封装
    什么是接口测试?如何进行接口测试
    类和实例
  • 原文地址:https://www.cnblogs.com/lyxcode/p/7571363.html
Copyright © 2020-2023  润新知