当我们用Filter时,往往需要使用一些辅助的service,在普通的java中,只要声明(set,get方法)后在spring-application配置文件中配置就可以了,但是由于Filter与Listener需要配置在web.xml文件中,所以它们的对象是由容器创建的。通常在Spring的application-context.xml配置文件中编写的bean由Spring负责创建,所以直接在Spring配置文件配置过滤器与监听器是无法达到注入目的的。这时就需要配置一个spring提供的代理类。web.xml中配置Filter如下:
<filter>
<filter-name>authFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>authFilterSeriver</param-value>
</init-param>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
其中配置的authFilterSeriver是配置spring文件中bean的id,如下图:
<bean id="authFilterSeriver" class="com.test.AuthFilter" ></bean>
这样, AuthFilter中就可以调用spring管理的service了。
同理,可以自己写一个代理类,类似spring的类DelegatingFilterProxy。
package com.test.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
//Filter 的代理类。系统所有的 Filter 共用此一个
public class DelegatingFilterProxy implements Filter {
private String targetFilterBean;
private Filter proxy;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
proxy.doFilter(servletRequest, servletResponse, filterChain);
}
@Override
public void init(FilterConfig config) throws ServletException {
this.targetFilterBean = config.getInitParameter("targetFilterBean");
ServletContext servletContext = null;
servletContext = config.getServletContext();
WebApplicationContext wac = null;
wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
this.proxy = (Filter) wac.getBean(this.targetFilterBean);
this.proxy.init(config);
}
@Override
public void destroy() {}
}