tomcat容器初始化顺序监听器–>过滤器–>servlet,因此springMVCservlet初始化之前,过滤器就已经初始化过了,如果在过滤器中需要注入spring容器管理的bean是注入不进去的,因此需要在spring监听器中初始化需要注入的bean,才能在过滤器中注入,而且过滤器的定义需要使用spring定义的DelegatingFilterProxy来实现,web.xml部分代码如下
如果要保留Filter原有的init,destroy方法的调用,还需要配置初始化参数targetFilterLifecycle为true,该参数默认为false,代码例子如下:
web.xml配置一
<filter>
<filter-name>clickstream</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>clickstreamFilter</param-value>
</init-param>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
<filter-name>clickstream</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>clickstreamFilter</param-value>
</init-param>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>clickstream</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>clickstream</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
web.xml配置二
<filter> <filter-name>clickstream</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> <init-param> <filter-mapping> <filter-name>clickstream</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
基本上没有太大区别
@Componen("clickstreamFilter") //这括号里面写不写一样的吧 public class ClickstreamFilter implements Filter { @Resource(name="locusRecordManager") private ILocusRecordManager locusRecordManager; public ILocusRecordManager getLocusRecordManager() { return locusRecordManager; } public void setLocusRecordManager(ILocusRecordManager locusRecordManager) { this.locusRecordManager = locusRecordManager; } }
spring配置
注入Filter类
<bean id="clickstreamFilter" class="com.ClickstreamFilter"> <property name="locusRecordManager"> //filter类的对象 <ref bean="locusRecordManager"/> //service类的id </property> </bean>
注入service