zoukankan      html  css  js  c++  java
  • 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);
    	}
    }
    
  • 相关阅读:
    前端常用设计模式和工作中应用场景思考
    webpack从零开始打造react项目(更新中...)
    操作系统-进程
    go语言web框架-如何使用gin教程+react实现web项目
    JavaScript逗号运算符的用法
    react的生命周期和使用
    在Vue项目中使用wangEditor
    TypeScript实现axios
    SpringBoot整合邮件发送(thymeleaf和freemarker)
    SpringBoot整合RabbitMQ
  • 原文地址:https://www.cnblogs.com/mzq123/p/11253553.html
Copyright © 2011-2022 走看看