为什么Spring没有像HttpServletResponse
这样的类RequestContextHolder?在某些情况下我需要访问响应对象。例如,spring security正在创建一个InteractiveSuccessEvent以成功登录。我的事件处理程序需要正确地为cookie设置一些值,我不知道修改HttpServletResponse
对象的明确方法。
编辑:处理程序示例
@Component
public class ActivityLoginSuccessEventHandler implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {
@Override
public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) {
//todo cookie
}
}
答案 0 :(得分:2)
我最终得到了一个简单的过滤器。
public class ResponseContextHolderFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
RequestAndResponseContextHolder.response(response);
} finally {
filterChain.doFilter(request, response);
}
}
}
public class RequestAndResponseContextHolder {
public static final String RESPONSE_NAME_AT_ATTRIBUTES =
ServletRequestAttributes.class.getName() + ".ATTRIBUTE_NAME";
public static HttpServletResponse response() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletResponse response = null;
if(requestAttributes != null) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
response = (HttpServletResponse) servletRequestAttributes.getAttribute(RESPONSE_NAME_AT_ATTRIBUTES, RequestAttributes.SCOPE_REQUEST);
}
return response;
}
public static HttpServletRequest request() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = null;
if(requestAttributes != null) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
request = servletRequestAttributes.getRequest();
}
return request;
}
public static void response(HttpServletResponse response) {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if(requestAttributes != null) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
servletRequestAttributes.setAttribute(RESPONSE_NAME_AT_ATTRIBUTES, response, RequestAttributes.SCOPE_REQUEST);
}
}
}
答案 1 :(得分:0)
如果您找不到更好的解决方案,那么您可以扩展UsernameAndPasswordAuthenticationFiter http://docs.spring.io/autorepo/docs/spring-security/3.0.x/apidocs/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.html(或您使用的AuthenticationFilter),您可以访问请求和响应。