Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring security: Cannot call sendRedirect() after the response has been committed [duplicate]

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)
like image 629
youssef Liouene Avatar asked Mar 24 '26 21:03

youssef Liouene


1 Answers

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);
like image 50
holmis83 Avatar answered Mar 26 '26 10:03

holmis83



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!