自定义注释 @WebFilterSort
实现源码: https://download.csdn.net/download/u013202238/12451011
使用demo, 创建三个Filter,分别为 MyFilter1,MyFilter2,MyFilter3,内容如下,分别指定Order为3、2、1
@WebFilterSort(order = 3)
public class MyFilter1 implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println(MyFilter1.class.getName() + " init");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println(MyFilter1.class.getName() + " before doFilter");
filterChain.doFilter(servletRequest, servletResponse);
System.out.println(MyFilter1.class.getName() + " after doFilter");
}
@Override
public void destroy() {
System.out.println(MyFilter1.class.getName() + " destroy");
}
}
无论使用@javax.servlet.annotation.WebFilter或@WebFilterSort注解注册的Filter默认都在web.xml部署描述符中的过滤器加载后加载,可以使用isMatchAfter更改加载顺序
以url-pattern 过滤的最先执行,以servlet-name 过滤的在全部url-pattern执行后执行
在web.xml中设置参数
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
< description>被扫描的过滤器的所在包< /description>
< param-name>filterPackage< /param-name>
< param-value>com.test.filter.pack< /param-value>
</context-param>
<context-param>
<description>是否扫描jar包中的类,默认为false不扫描</description>
<param-name>filterInitScanJar</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<description>是否打印过滤器初始化信息(按排序顺序),默认false不打印,如果不打印可以不配置该参数</description>
<param-name>filterInitDebug</param-name>
<param-value>false</param-value>
</context-param>
</web-app>
filterPackage 必填,包范围越小越好
filterInitScanJar 选填 是否扫描jar包中的类,默认为false不扫描
filterInitDebug 选填 是否打印过滤器初始化信息(按排序顺序),默认false不打印,如果不打印可以不配置该参数
在未指定排序时@WebFilter执行循序是按照被扫描到的循序执行的,
使用@WebFilterSort注解后,可以指定执行顺序,执行Filter
注解参数说明, 个参数等效于 @WebFilter中的参数
限定符和类型 | 必需的元素和说明 |
---|---|
int | value (等同于order)
排序优先级
|
限定符和类型 | 可选元素和说明 |
---|---|
boolean | asyncSupported
Declares whether the filter supports asynchronous operation mode.(默认false)
|
DispatcherType[] | dispatcherTypes
The dispatcher types to which the filter applies
default {DispatcherType.REQUEST}; |
java.lang.String | displayName
The display name of the filter,默认值 ""
|
java.lang.String | filterName
The name of the filter,默认值 ""
|
boolean | isMatchAfter
表示该过滤器相对于部署描述符中过滤器的顺序
如果使用的参数为false,那么该过滤器映射将在部署描述符中描述的所有过滤器加载前进行加载, 如果为true( 默认 ),那么部署描述符中的过滤器将先被加载 |
java.lang.String[] | servletNames
The names of the servlets to which the filter applies.
|
java.lang.String[] | urlPatterns
The URL patterns to which the filter applies,default {"/*"}
|