spring – 为什么没有Request的持有者类,如RequestContextHolder

为什么
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);
      }
   }
}
点赞