执子之手

与子偕老


  • 首页

  • 分类

  • 归档

  • 标签

  • 关于

  • 搜索
close

DelegatingFilterProxy源码分析

时间: 2017-06-02   |   分类: 开发     |   阅读: 2068 字 ~5分钟   |   访问: 0

1. 背景

1<filter>
2	<filter-name>springSecurityFilterChain</filter-name>
3	<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
4</filter>
5
6<filter-mapping>
7	<filter-name>springSecurityFilterChain</filter-name>
8	<url-pattern>/documentation/*</url-pattern>
9</filter-mapping>

用过Spring Security的人都会熟悉以上代码,一般教程上都会说明,使用Spring Security就需要在web.xml中指定以上代码。从这个配置中,可能会给我们造成一个错觉,以为DelegatingFilterProxy类就是springSecurity的入口,但其实这个类位于spring-web这个jar下面,说明这个类本身是和springSecurity无关。

2. 真相

DelegatingFilterProxy类继承于抽象类GenericFilterBean,间接地implement 了javax.servlet.Filter接口,Servlet容器在启动时,首先会调用Filter的init方法,GenericFilterBean的作用主要是可以把Filter的初始化参数自动地set到继承于GenericFilterBean类的Filter中去。在其init方法的如下代码就是做了这个事:

1PropertyValues pvs = new FilterConfigPropertyValues(filterConfig, this.requiredProperties);
2BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
3ResourceLoader resourceLoader = new ServletContextResourceLoader(filterConfig.getServletContext());
4bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, this.environment));
5initBeanWrapper(bw);
6bw.setPropertyValues(pvs, true);

另外在init方法中调用了initFilterBean()方法,该方法是GenericFilterBean类是特地留给子类扩展用的:

 1Override
 2protected void initFilterBean() throws ServletException {
 3	synchronized (this.delegateMonitor) {
 4		if (this.delegate == null) {
 5			// If no target bean name specified, use filter name.
 6			if (this.targetBeanName == null) {
 7				this.targetBeanName = getFilterName();
 8			}
 9			// Fetch Spring root application context and initialize the delegate early,
10			// if possible. If the root application context will be started after this
11			// filter proxy, we'll have to resort to lazy initialization.
12			WebApplicationContext wac = findWebApplicationContext();
13			if (wac != null) {
14				this.delegate = initDelegate(wac);
15			}
16		}
17	}
18}

可以看出上述代码首先看Filter是否提供了targetBeanName初始化参数,如果没有提供则直接使用filter的name做为beanName,产生了beanName后,由于我们在web.xml的filter的name是springSecurityFilterChain,从spring的IOC容器中取出bean的代码是initDelegate方法,下面是该方法代码:

1protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
2        Filter delegate = wac.getBean(getTargetBeanName(), Filter.class);
3        if (isTargetFilterLifecycle()) {
4            delegate.init(getFilterConfig());
5        }
6        return delegate;
7}

通过跟踪代码,发现取出的bean是org.springframework.security.FilterChainProxy,该类也是继承于GenericFilterBean,取出bean后,判断targetFilterLifecycle属性是false还是true,决定是否调用该类的init方法。这个FilterChainProxy bean实例最终被保存在DelegatingFilterProxy类的delegate属性里,

下面看一下DelegatingFilterProxy类的doFilter方法 :

 1public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
 2            throws ServletException, IOException {
 3 
 4        // Lazily initialize the delegate if necessary.
 5        Filter delegateToUse = null;
 6        synchronized (this.delegateMonitor) {
 7            if (this.delegate == null) {
 8                WebApplicationContext wac = findWebApplicationContext();
 9                if (wac == null) {
10                    throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?");
11                }
12                this.delegate = initDelegate(wac);
13            }
14            delegateToUse = this.delegate;
15        }
16 
17        // Let the delegate perform the actual doFilter operation.
18        invokeDelegate(delegateToUse, request, response, filterChain);
19    }

真正要关注invokeDelegate(delegateToUse, request, response, filterChain);这句代码,在下面可以看出DelegatingFilterProxy类实际是用其delegate属性即org.springframework.security.FilterChainProxy实例的doFilter方法来响应请求。

1protected void invokeDelegate(
2            Filter delegate, ServletRequest request, ServletResponse response, FilterChain filterChain)
3            throws ServletException, IOException {
4 
5        delegate.doFilter(request, response, filterChain);
6    }

以上就是DelegatingFilterProxy类的一些内部运行机制,其实主要作用就是一个代理模式的应用,可以把servlet 容器中的filter同spring容器中的bean关联起来。

此外还要注意一个DelegatingFilterProxy的一个初始化参数:targetFilterLifecycle ,其默认值为false 。 但如果被其代理的filter的init()方法和destry()方法需要被调用时,需要设置targetFilterLifecycle为true。具体可见DelegatingFilterProxy中的如下代码:

 1protected void initFilterBean() throws ServletException {
 2        synchronized (this.delegateMonitor) {
 3            if (this.delegate == null) {
 4                // If no target bean name specified, use filter name.
 5                if (this.targetBeanName == null) {
 6                    this.targetBeanName = getFilterName();
 7                }
 8                // Fetch Spring root application context and initialize the delegate early,
 9                // if possible. If the root application context will be started after this
10                // filter proxy, we'll have to resort to lazy initialization.
11                WebApplicationContext wac = findWebApplicationContext();
12                if (wac != null) {
13                    this.delegate = initDelegate(wac);
14                }
15            }
16        }
17    }
18 
19 
20protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
21        Filter delegate = wac.getBean(getTargetBeanName(), Filter.class);
22        if (isTargetFilterLifecycle()) {    //注意这行
23            delegate.init(getFilterConfig());
24        }
25        return delegate;
26    }

3. 结论

DelegatingFilterProxy是Spring-web中的一个通用Filter,它可以达到如下目的,解决如下问题: 通过Delegate模式,将Filter的功能转移到一个Spring管理的Bean上去,这样这个Bean就可以实现Filter功能,而且又享受了Spring带来的好处。 另外:这个Bean需要实现Filter接口。

4. 结论2

当不指定targetBeanName的时候,DelegatingFilterProxy会使用FilterName来查找指定的Bean并完成初始化。这也解释了,使用Spring Security的时候,要求的FilterName一定要是:springSecurityFilterChain。

#Spring# #Security# #Java#
Nginx配置导致的SSL证书认证失败
使用Docker+Apache2+WebSVN搭建SVN服务器
  • 文章目录
  • 站点概览
Orchidflower

Orchidflower

Do one thing at a time, and do well.

76 日志
6 分类
83 标签
GitHub 知乎 OSC 豆瓣
  • 1. 背景
  • 2. 真相
  • 3. 结论
  • 4. 结论2
© 2009 - 2022 执子之手
Powered by - Hugo v0.104.3
Theme by - NexT
ICP - 鲁ICP备17006463号-1
0%