why there is not a holder class for Response like RequestContextHolder

前端 未结 2 667
粉色の甜心
粉色の甜心 2021-01-19 21:31

Why Spring does not have a class like RequestContextHolder for HttpServletResponse? There are some cases I need to access response object. For example spring se

相关标签:
2条回答
  • 2021-01-19 22:07

    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);
          }
       }
    }
    
    0 讨论(0)
  • 2021-01-19 22:23

    If you do not find a better solution, then you can extend the UsernameAndPasswordAuthenticationFiter http://docs.spring.io/autorepo/docs/spring-security/3.0.x/apidocs/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.html (or the AuthenticationFilter you use instead) there you have Access to the Request and Response.

    0 讨论(0)
提交回复
热议问题