定义2个Filter,filter1过滤.htm和.json结尾的url,filter2过滤.htm和.xml结尾的url。
1、init()方法执行顺序:先执行filter2的init()方法,后执行filter1的init()方法。
因为Filter是
责任链模式的,上一级对象包含下一级对象的指针,所以创建顺序在web.xml中是从后往前的。
2、同一mapping url的doFilter()执行顺序,如*.htm:先执行filter1的doFilter()方法,后执行filter2的doFilter()方法,会进行链式调用。在web.xml中,是按照从前往后的顺序执行。
3、当全部Filter执行完成,且没有return时,会调用url映射的servlet的service()方法。service()方法执行完后,会逐层放回Filter的doFilter()方法,有点像spring的aop。
4、不同mapping url的doFilter()执行顺序,如*.json:只会调用filter1的doFilter()方法。mapping url只会执行对应Filter的doFilter()方法。
5、Tomcat7的Filter实现类为ApplicationFilterChain,创建代码如下:
class="java">
ApplicationFilterFactory factory =
ApplicationFilterFactory.getInstance();
ApplicationFilterChain filterChain =
factory.createFilterChain(request, wrapper, servlet);
<filter>
<filter-name>filter1</filter-name>
<filter-class>filter.Filter1</filter-class>
</filter>
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>*.htm</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>*.json</url-pattern>
</filter-mapping>
<filter>
<filter-name>filter2</filter-name>
<filter-class>filter.Filter1</filter-class>
</filter>
<filter-mapping>
<filter-name>filter2</filter-name>
<url-pattern>*.htm</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filter2</filter-name>
<url-pattern>*.xml</url-pattern>
</filter-mapping>