本文介绍了为什么没有像RequestContextHolder这样的Response持有人类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么Spring没有HttpServletResponse
之类的RequestContextHolder之类的类?在某些情况下,我需要访问响应对象.例如,spring security正在为成功登录创建一个InteractiveSuccessEvent.我的事件处理程序需要正确地为cookie设置一些值,而我不知道修改HttpServletResponse
对象的明确方法.
Why Spring does not have a class like RequestContextHolder for HttpServletResponse
? There are some cases I need to access response object. For example spring security is creating an InteractiveSuccessEvent for successful logins. My event handler needs properly set some values to cookie and I do not know an explicit way to modify HttpServletResponse
object.
处理程序示例
@Component
public class ActivityLoginSuccessEventHandler implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {
@Override
public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) {
//todo cookie
}
}
推荐答案
我最终得到了一个简单的过滤器.
I ended up with a simple filter.
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);
}
}
}
这篇关于为什么没有像RequestContextHolder这样的Response持有人类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!