Spring Security Web 5.1.2 源码解析 -- RequestCacheAwareFilter

版权声明:本文为博主原创文章,未经博主允许不得转载。 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中,而且不是所有的请求都会被缓存,而是只有符合以下条件的请求才被缓存 :

  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

猜你喜欢

转载自blog.csdn.net/andy_zhang2007/article/details/84862635
今日推荐