Spring Security Web 5.1.2 原始碼解析 -- RequestCacheAwareFilter
阿新 • • 發佈:2018-12-12
概述
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