[Solved] java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

Project scenario:

Spring boot project, user-defined filter, intercept requests and process business.


Problem Description:

When you start the project access interface, you call resp.sendRedirect () in the custom filter.


Cause analysis:

After the response has been submitted, the sendredirect() method cannot be called.

In fact, chain. Dofilter (req, resp) is executed; Cannot use sendredirect() of resp object after

So looking at the code, we find that:

...

  HttpServletRequest httpRequest = (HttpServletRequest) request;
  HttpServletResponse httpResponse = (HttpServletResponse) response;
  ....
  boolean flag = getStatus();
  if (flag) {
      ....
      chain.doFilter(request, response);
  }
  httpResponse.sendRedirect(“xxxx”);
...

if the judged flag is true, chain.dofilter (request, response) will be executed, and httpresponse.sendredirect (“XXXX”) </ font> will be executed after execution


Solution:

After chain. Dofilter (request, response), add return to end the current method.

...

  HttpServletRequest httpRequest = (HttpServletRequest) request;
  HttpServletResponse httpResponse = (HttpServletResponse) response;
  ....
  boolean flag = getStatus();
  if (flag) {
      ....
      chain.doFilter(request, response);
      return;
  }
  httpResponse.sendRedirect(“xxxx”);
...


Read More: