JAVA && Spring && SpringBoot2.x — 学习目录
源码:org.springframework.web.filter.DelegatingFilterProxy
Filter过滤器是Servlet容器来管理,一般我们需要web.xml文件中配置Filter链,需要继承如下接口:
public interface Filter {
void init(FilterConfig var1) throws ServletException;
void doFilter(ServletRequest var1, ServletResponse var2, FilterChain var3)
throws IOException, ServletException;
void destroy();
}
而DelegatingFilterProxy (授权拦截器代理)是一个Servlet Filter的代理。它的优点如下:
- 通过spring容器来管理servlet filter的生命周期。
- 如果filter中需要Spring容器的实例,可以通过spring直接注入。
- 读取配置文件这些便利操作都可以通过Spring来配置文件实现。
首先在web.xml中配置:
<!--测试DelegatingFilterProxy针对于普通的Filter的作用-->
<filter>
<filter-name>myProxyFilter</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>
<filter-mapping>
<filter-name>myProxyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
注意一个DelegatingFilterProxy的一个初始化参数:targetFilterLifecycle ,其默认值为false 。 但如果被其代理的filter的init()方法和destry()方法需要被调用时,需要设置targetFilterLifecycle为true
@Component
public class MyProxyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("【MyProxyFilter初始化操作】");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("【MyProxyFilter拦截操作】");
chain.doFilter(request,response);
}
@Override
public void destroy() {
}
}
需要注意的是:在Spring中配置的bean的name要和web.xml中的<filter-name>保持相同。
DelegatingFilterProxy类的一些内部机制,其主要作用就是一个代理模式的应用,可以把servlet容器中的filter对象和Spring容器中的Bean关联起来。