Spring安全性:在提交响应后无法调用sendRedirect()

时间:2016-02-22 14:19:30

标签: java spring web-services spring-security

我正在使用以下代码进行注销:

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);
    }

 }

}

但是当调用/注销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)

1 个答案:

答案 0 :(得分:2)

不,在您写完一个正文之后,您无法使用sendRedirect,因为这样的回复就是#34;已经提交了#34;。

如果您想要使用自定义正文进行重定向,则可以在编写响应正文之前设置相应的重定向

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