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

  • 相关阅读:
    配置samba
    extern c
    剑指offer 孩子们的游戏
    剑指offer 扑克牌顺子
    剑指offer 翻转单词顺序列
    剑指offer 左旋转字符串
    mysql查看或显示当前存在多少数据库
    vim替换
    平衡二叉树
    将employees表的所有员工的last_name和first_name拼接起来作为Name,中间以一个空格区分
  • 原文地址:https://www.cnblogs.com/lyxcode/p/7571363.html
Copyright © 2011-2022 走看看