当我们需要在自定义Filter类中注入service or dao时,我们可以通过以下的方式实现。
1、编写自定义的CustomFilter类(基于注解的),实现Filter接口,重写init、doFilter、destroy方法。
@Component
public class CustomFilter implements Filter {
@Autowired
private UsersService usersService;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println(usersService);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
}
@Override
public void destroy() {
}
}
2、配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!-- springmvc配置 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!-- 字符集配置 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 自定义过滤器配置 -->
<filter>
<filter-name>customFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>customFilter</filter-name>
<url-pattern>/xx/xx/xxxAdd</url-pattern>
</filter-mapping>
</web-app>
3、springmvc-servlet.xml配置
添加:<context:component-scan base-package="com.xxx" /> ,如果使用xml装配的方式,可以直接爱配置文件中添加
<bean name="customFilter" class="com.xxx.x.Filter.CompareTaskFilter"></bean>,CustomFilter类中去掉注解。
注意:bean的name要和web.xml中的<filter-name>一样。
4、测试输出usersService 的地址(表示注入成功)
com.xxx.xxx.service.UsersService@18c72234
5、总结
观察web.xml 自定义过滤器的配置中“DelegatingFilterProxy” ,DelegatingFilterProxy是对servlet filter的代理,用这个类的好处主要是通过Spring容器来管理servlet filter的生命周期,还有就是如果filter中需要一些Spring容器的实例,可以通过spring直接注入,另外读取一些配置文件这些便利的操作都可以通过Spring来配置实现。
如果要保留Filter原有的init,destroy方法的调用,还需要配置初始化参数targetFilterLifecycle为true,该参数默认为false。
<filter>
<filter-name>compareTaskFilter</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>
</filter>