2013-12-11 51 views
4

爲什麼Spring沒有像RequestContextHolder這樣的類爲HttpServletResponse?有些情況下我需要訪問響應對象。例如,spring安全性正在爲成功登錄創建一個InteractiveSuccessEvent。我的事件處理程序需要正確地將一些值設置爲cookie,並且我不知道明確的方法來修改HttpServletResponse對象。爲什麼沒有響應持有者類如RequestContextHolder

編輯:處理器

@Component 
public class ActivityLoginSuccessEventHandler implements ApplicationListener<InteractiveAuthenticationSuccessEvent> { 

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

你可以顯示你的事件處理程序嗎? –

+0

@SotiriosDelimanolis增加了一個例子 – Cemo

回答

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); 
     } 
    } 
} 
相關問題