Spring Security3源码分析-FilterChainProxy执行过程分析
通过FilterChainProxy的初始化、自定义标签的分析后,Spring Security需要的运行环境已经准备好了。
这样当用户访问应用时,过滤器就开始工作了。web.xml配置的Filter:org.springframework.web.filter.DelegatingFilterProxy就不介绍了,该类仅仅是初始化一个FilterChainProxy,然后把所有拦截的请求交给FilterChainProxy处理。
FilterChainProxy的doFilter方法如下
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //FilterInvocation类封装了request、response、chain //在方法中传递 FilterInvocation fi = new FilterInvocation(request, response, chain); //获取http标签中创建的所有Filter List<Filter> filters = getFilters(fi.getRequestUrl()); if (filters == null || filters.size() == 0) { if (logger.isDebugEnabled()) { logger.debug(fi.getRequestUrl() + filters == null ? " has no matching filters" : " has an empty filter list"); } chain.doFilter(request, response); return; } //把实际doFilter任务交给VirtualFilterChain处理 VirtualFilterChain virtualFilterChain = new VirtualFilterChain(fi, filters); virtualFilterChain.doFilter(fi.getRequest(), fi.getResponse()); }
private static class VirtualFilterChain implements FilterChain { private FilterInvocation fi; private List<Filter> additionalFilters; private int currentPosition = 0; private VirtualFilterChain(FilterInvocation filterInvocation, List<Filter> additionalFilters) { this.fi = filterInvocation; this.additionalFilters = additionalFilters; } public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { //判断过滤器的个数是否与当前位置相等 if (currentPosition == additionalFilters.size()) { if (logger.isDebugEnabled()) { logger.debug(fi.getRequestUrl() + " reached end of additional filter chain; proceeding with original chain"); } fi.getChain().doFilter(request, response); } else { //当前位置加一 currentPosition++; //根据当前位置从过滤器列表中取出一个Filter Filter nextFilter = additionalFilters.get(currentPosition - 1); if (logger.isDebugEnabled()) { logger.debug(fi.getRequestUrl() + " at position " + currentPosition + " of " + additionalFilters.size() + " in additional filter chain; firing Filter: '" + nextFilter + "'"); } //执行取出Filter的doFilter方法 nextFilter.doFilter(request, response, this); } } }
nextFilter.doFilter(request, response, this);