我们在使用spring security时发现配置了一个过滤器
<!--security的过滤器-->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
查看DelegatingFilterProxy源码发现没有init方法,找到父类GenericFilterBean发现父类有init方法,并且这个方法中获取了filter的配置文件,还调用了DelegatingFilterProxy的initFilterBean()方法。
this.filterConfig = filterConfig;
initFilterBean();
回到DelegatingFilterProxy的initFilterBean()方法
方法中获取了配置文件中的名字
this.targetBeanName = getFilterName();
protected String getFilterName() {
return (this.filterConfig != null ? this.filterConfig.getFilterName() : this.beanName);
}
并根据名字获取对应对象
this.delegate = initDelegate(wac);
protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
String targetBeanName = getTargetBeanName();
Assert.state(targetBeanName != null, "No target bean name set");
Filter delegate = wac.getBean(targetBeanName, Filter.class);
if (isTargetFilterLifecycle()) {
delegate.init(getFilterConfig());
}
return delegate;
}
到此初始化结束
然后看dofilter方法中,都是使用初始化方法获取的对象
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// Lazily initialize the delegate if necessary.
Filter delegateToUse = this.delegate;
if (delegateToUse == null) {
synchronized (this.delegateMonitor) {
delegateToUse = this.delegate;
if (delegateToUse == null) {
WebApplicationContext wac = findWebApplicationContext();
if (wac == null) {
throw new IllegalStateException("No WebApplicationContext found: " +
"no ContextLoaderListener or DispatcherServlet registered?");
}
delegateToUse = initDelegate(wac);
}
this.delegate = delegateToUse;
}
}
//上面主要是对delegate对象的校验,真正的逻辑在下面方法里
// Let the delegate perform the actual doFilter operation.
invokeDelegate(delegateToUse, request, response, filterChain);
}
进入invokeDelegate方法,发现实际上每次过滤器都会去执行我们给的名字生成的对应对象的doFilter方法。
protected void invokeDelegate(
Filter delegate, ServletRequest request, ServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
delegate.doFilter(request, response, filterChain);
}
了解了基本流程,不过为什么不直接在当前配置的filter中直接进行流程控制呢,为啥要给其他的filter控制以后有时间再深入了解
还有security的配置文件解析。以后了解