servlet中的IllegalStateException

 2020-08-01 13:17  阅读(819)
文章分类:Spring boot

IllegalStateException在java web开发中比较常见,IllegalStateException的根本原因是java servlet在提交响应后,还尝试写内容

所以避免IllegalStateException的一个好方法就是提交响应,比如forward或者redirect之后,就不要再写内容,一个方法是在redirect之后加上return;

比如这个比较常见的IllegalStateException,原因就是已经sendRedirect,提交响应了,然后还尝试写内容,这样就导致了IllegalStateException

Java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

下面给出会异常的代码:

public class LoginFilter extends OncePerRequestFilter{
       ...
        @Override
        protected void doFilterInternal(final HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {
            HttpServletRequest wrappedRequest = new RemoteUserRequestWrapper(request);
            if (StringUtils.isEmpty(wrappedRequest.getRemoteUser()) ) {
                response.sendRedirect("login.do");
                //return;
            }
            filterChain.doFilter(new RemoteUserRequestWrapper(request), response);
        }
    }

这段代码response.sendRedirect之后,跳到 login.do,login.do里的代码逻辑是有再次重定向等等逻辑的,然后Filter里代码,没return,执行后是会IllegalStateException的

然后只要在sendRedirect之后加上return就可以:

public class LoginFilter extends OncePerRequestFilter{
       ...
        @Override
        protected void doFilterInternal(final HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {
            HttpServletRequest wrappedRequest = new RemoteUserRequestWrapper(request);
            if (StringUtils.isEmpty(wrappedRequest.getRemoteUser()) ) {
                response.sendRedirect("login.do");
                return;
            }
            filterChain.doFilter(new RemoteUserRequestWrapper(request), response);
        }
    }

来源:https://www.cnblogs.com/mzq123

点赞(2)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> servlet中的IllegalStateException

相关推荐