过滤器链
可以使用多个过滤器组成一个过滤器链进行协同工作。
现在我们新建两个Filter,取名Filter1和Filter2,并且分别在这两个过滤器的doFilter方法上编写打印的代码
Filter1的代码如下:
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
System.out.println("Filter1 begin");
arg2.doFilter(arg0, arg1);
System.out.println("Filter1 end");
}
Filter2的代码如下:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("Filter2 begin");
chain.doFilter(request, response);
System.out.println("Filter2 end");
}
然后在web.xml里面配置:
<filter>
<filter-name>filter1</filter-name>
<filter-class>Filter1</filter-class>
</filter>
<filter>
<filter-name>filter2</filter-name>
<filter-class>Filter2</filter-class>
</filter>
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filter2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
这里为了测试方便,把url都配置成/*,即拦截所有
部署项目,启动tomcat并访问工程
我们会发现在控制台会打印如下语句:
Filter1 begin
Filter2 begin
Filter2 end
Filter1 end
这两个过滤器执行的顺序是:
1,先执行了Filter1,在执行Filter1的arg2.doFilter(arg0, arg1)时就去执行Filter2
2,代码执行到Filter2的chain.doFilter(request, response);时就去执行某个jsp或者servlet
3 ,最后又回过来执行Filter2的后半段和Filter1的后半段。
那么为什么会在最开始执行Filter1呢?
这个与filter-mapping的配置顺序有关,假如说某些过滤器都能拦截某个url,那么filter-mapping配置越靠前,执行顺序也越靠前。