如何使用WAR中的注释定义servlet过滤器执行顺序
如果我们在WAR自己的 web.xml
中定义特定于webapp的servlet过滤器,那么过滤器的执行顺序将与它们的定义顺序相同在 web.xml
。
If we define webapp specific servlet filters in WAR's own web.xml
, then the order of execution of the filters will be the same as the order in which they are defined in the web.xml
.
但是,如果我们使用 @WebFilter定义这些过滤器
注释,过滤器的执行顺序是什么,我们如何确定执行顺序?
But, if we define those filters using @WebFilter
annotation, what is the order of execution of filters, and how can we determine the order of execution?
您确实无法使用定义过滤器执行顺序 @WebFilter
注释。但是,为了最小化 web.xml
的使用,仅使用 filterName
注释所有过滤器就足够了,这样你就可以了不需要< filter>
定义,只需要按所需顺序的< filter-mapping>
定义。
You can indeed not define the filter execution order using @WebFilter
annotation. However, to minimize the web.xml
usage, it's sufficient to annotate all filters with just a filterName
so that you don't need the <filter>
definition, but just a <filter-mapping>
definition in the desired order.
例如,
@WebFilter(filterName="filter1")
public class Filter1 implements Filter {}
@WebFilter(filterName="filter2")
public class Filter2 implements Filter {}
在 web.xml
中就是这样:
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>/url1/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filter2</filter-name>
<url-pattern>/url2/*</url-pattern>
</filter-mapping>
如果您想将网址格式保留在 @WebFilter
,那么你可以这样做,
If you'd like to keep the URL pattern in @WebFilter
, then you can just do like so,
@WebFilter(filterName="filter1", urlPatterns="/url1/*")
public class Filter1 implements Filter {}
@WebFilter(filterName="filter2", urlPatterns="/url2/*")
public class Filter2 implements Filter {}
但是你仍然应该保留< url-pattern>
在 web.xml
中,因为根据XSD需要它,尽管它可以为空:
but you should still keep the <url-pattern>
in web.xml
, because it's required as per XSD, although it can be empty:
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern />
</filter-mapping>
<filter-mapping>
<filter-name>filter2</filter-name>
<url-pattern />
</filter-mapping>
无论采用何种方法,这一切都将在Tomcat中失败,直到版本7.0.28,因为它会在存在时窒息< filter-mapping>
没有< filter>
。另请参阅使用Tomcat,@ WebFilter不能与< filter-mapping>一起使用在web.xml内
Regardless of the approach, this all will fail in Tomcat until version 7.0.28 because it chokes on presence of <filter-mapping>
without <filter>
. See also Using Tomcat, @WebFilter doesn't work with <filter-mapping> inside web.xml