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

  • 相关阅读:
    aria2
    Tomcat Manager Config
    selenium 入门(Java)
    java线上cpu、内存问题排查方法
    Java多线程知识点
    《Java7并发编程实战手册》读书笔记
    《Java并发编程的艺术》读书笔记
    centos7安装mysql
    Linux用户配置文件
    metasploit魔鬼训练营靶机环境搭建(第二章)
  • 原文地址:https://www.cnblogs.com/chenyongblog/p/6010793.html
Copyright © 2011-2022 走看看