概述
Spring Security Web
對請求提供了緩存機制,如果某個請求被緩存,它的提取和使用是交給
RequestCacheAwareFilter
完成的。
系統在啟動時,
Spring Security Web
會首先嘗試從容器中擷取一個
RequestCache bean
,擷取失敗的話,會建構一個預設的
RequestCache
對象,然後執行個體化該過濾器 。
如果容器中不存在
RequestCache bean
,
Spring Security Web
所使用的預設
RequestCache
是一個
HttpSessionRequestCache
,它會将請求儲存在
http session
中,而且不是所有的請求都會被緩存,而是隻有符合以下條件的請求才被緩存 :
- 必須是 GET favicon.*
- 并且不能是 application.json
- 并且不能是 XMLHttpRequest (也就是一般意義上的 ajax 請求)
上面請求緩存條件的定義在 RequestCacheConfigurer#createDefaultSavedRequestMatcher
中。
源代碼分析
public class RequestCacheAwareFilter extends GenericFilterBean {
private RequestCache requestCache;
// 使用http session 作為請求緩存的構造函數
public RequestCacheAwareFilter() {
this(new HttpSessionRequestCache());
}
// 外部指定請求緩存對象的構造函數
public RequestCacheAwareFilter(RequestCache requestCache) {
Assert.notNull(requestCache, "requestCache cannot be null");
this.requestCache = requestCache;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// 嘗試從請求緩存中擷取跟目前請求比對的被緩存的請求
HttpServletRequest wrappedSavedRequest = requestCache.getMatchingRequest(
(HttpServletRequest) request, (HttpServletResponse) response);
// 如果從緩存中擷取的請求不為空,使用它繼續filter chain的執行,
// 否則使用參數request繼續filter chain的執行
chain.doFilter(wrappedSavedRequest == null ? request : wrappedSavedRequest,
response);
}
}
相關文章
Spring Security Web 5.1.2 源碼解析 – 安全相關Filter清單
Spring Security Web 5.1.2 源碼解析 – HttpSessionRequestCache