Stack Exchange
Spring security: Cannot call sendRedirect() after the response has been committed
I'm using the following code for logout:
public class LogoutHandler extends SimpleUrlLogoutSuccessHandler {


@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
        throws IOException, ServletException {
    if(!response.isCommitted()) {
        String targetURL = "myUrl";
        response.setContentType(MediaType.TEXT_PLAIN_VALUE);
        response.getWriter().write(target);
        response.getWriter().flush();
        response.getWriter().close();
        getRedirectStrategy().sendRedirect(request, response, targetURL);
    }

 }

}

But when calling /logout WS I got the following exception:
 java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:494)
at javax.servlet.http.HttpServletResponseWrapper.sendRedirect(HttpServletResponseWrapper.java:138)
at org.springframework.security.web.firewall.FirewalledResponse.sendRedirect(FirewalledResponse.java:26)
at javax.servlet.http.HttpServletResponseWrapper.sendRedirect(HttpServletResponseWrapper.java:138)


you simply can't do a sendRedirect after you have flushed the response

how can we correct my code?

But then how are we supposed to use onLogoutSuccess? Without a redirect?

No, you can't use sendRedirect after you have written a body because then the response is "committed".
If you want a redirect with custom body, you can set the equivalent of doing a redirect before writing the response body:
response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
response.setHeader("Location", targetURL);


Now I don't have the exception but I don't redirect to target page.

I using embedded Tomcat Spring application. This setHeader work, but no sure why setError then sendRedirect will raise exception, but run in standalone tomcat don't raise exception...

But then how are we supposed to use onLogoutSuccess? Without a redirect?
