This question already has answers here:
java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

(8个答案)


3年前关闭。




我使用以下代码注销:
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);
    }

 }

}

但是当调用/ logout WS时,出现以下异常:
 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)

最佳答案

不可以,编写正文后就不能使用sendRedirect,因为这样响应是“已提交”。

如果要使用自定义正文进行重定向,则可以设置等效的方式,以在编写响应正文之前进行重定向:

response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
response.setHeader("Location", targetURL);

10-06 12:54