版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/andy_zhang2007/article/details/84862635
概述
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