servlet中的IllegalStateException

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);
    }
}

猜你喜欢

转载自www.cnblogs.com/mzq123/p/11253553.html