Cannot call sendRedirect() after the response has been committed

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangjingao/article/details/82352144

Cannot call sendRedirect() after the response has been committed 异常

对于http的response,如果已经进行了提交(重定向,请求转发,过滤器中的放行),则不能对response再进行任何操作,比如修改,比如再次提交。

对于已经提交的resposne,该方法并不会结束(和return不一样),它依然会继续往下执行,所以如果你在提交后继续执行的代码仍然会运行的提交response一样会导致这个错误。

比如:

  1. 下面的代码会因为在上面放行提交了response,现在又操作resposne而报错,是因为过滤器放行并不会返回方法,方法依然向下执行

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        boolean boo = "你的判断条件";
        if (boo) {
            log.info("enter chain");
            chain.doFilter(request, response);
            //return;
        }
        //此处就会因为在上面放行提交了response,现在又操作resposne而报错
        httpResponse.sendRedirect(TOLOGINURL);

2.下面的代码会因为在提交(重定向)后又再次提交而报错,因为重定向后依然会继续执行


httpResponse.sendRedirect(TOLOGINURL);
//此处会因为在提交(重定向)后又再次提交而报错
httpResponse.sendRedirect(TOLOGINURL);

解决方法就是在提交之后return;,或者检查逻辑不会再次进入提交。

猜你喜欢

转载自blog.csdn.net/zhangjingao/article/details/82352144