gpt4 book ai didi

spring - 为什么没有像 RequestContextHolder 这样的 Response 持有者类

转载 作者:行者123 更新时间:2023-12-01 03:52:53 25 4
gpt4 key购买 nike

为什么 Spring 对于 HttpServletResponse 没有像 RequestContextHolder 这样的类?在某些情况下,我需要访问响应对象。例如,spring security 正在为成功登录创建一个 InteractiveSuccessEvent。我的事件处理程序需要为 cookie 正确设置一些值,但我不知道修改 HttpServletResponse 的显式方法目的。

编辑:处理程序示例

@Component
public class ActivityLoginSuccessEventHandler implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {

@Override
public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) {
//todo cookie
}
}

最佳答案

我最终得到了一个简单的过滤器。

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

关于spring - 为什么没有像 RequestContextHolder 这样的 Response 持有者类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20531204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com