1. 程式人生 > >Spring Security Web 5.1.2 原始碼解析 -- RequestCacheAwareFilter

Spring Security Web 5.1.2 原始碼解析 -- RequestCacheAwareFilter

概述

Spring Security Web對請求提供了快取機制,如果某個請求被快取,它的提取和使用是交給RequestCacheAwareFilter完成的。

系統在啟動時,Spring Security Web會首先嚐試從容器中獲取一個RequestCache bean,獲取失敗的話,會構建一個預設的RequestCache物件,然後例項化該過濾器 。

如果容器中不存在RequestCache bean,Spring Security Web所使用的預設RequestCache是一個HttpSessionRequestCache,它會將請求儲存在http session

中,而且不是所有的請求都會被快取,而是隻有符合以下條件的請求才被快取 :

  1. 必須是 GET /**
  2. 並且不能是 /**/favicon.*
  3. 並且不能是 application.json
  4. 並且不能是 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