filter中的DelegatingFilterProxy使用事例

  最近发现在filter内使用DelegatingFilterProxy过滤内容,那么为什么不用自带的Filter而使用Spring的DelegatingFilterProxy哪?最后才明白是因为filter的类里面使用了Spring的注解,所以也必须也使用Spring的DelegatingFilterProxy。详细说明如下:

  DelegatingFilterProxy就是一个对于servlet filter的代理,用这个类的好处主要是通过Spring容器来管理servlet filter的生命周期,还有就是如果filter中需要一些Spring容器的实例,可以通过spring直接注入,另外读取一些配置文件这些便利的操作都可以通过Spring来配置实现。

  DelegatingFilterProxy的使用方法,首先在web.xml中配置:

<filter>
    <filter-name>myFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

  然后在Spring的配置文件中,配置具体的Filter类的实例,例如:<bean name="myFilter" class="com.taobao.MyFilter"></bean>

  在Spring中配置的bean的name要和web.xml中的<filter-name>一样,或者在DelegatingFilterProxy的filter配置中配置初始参数:targetBeanName,对应到Spring配置中的beanname。如果要保留Filter原有的init,destroy方法的调用,还需要配置初始化参数targetFilterLifecycle为true,该参数默认为false。

原文地址:https://www.cnblogs.com/liqiu/p/3409123.html