如何使用 WAR 中的注释定义 servlet 过滤器的执行顺序 [英] How to define servlet filter order of execution using annotations in WAR
问题描述
如果我们在 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
注释所有过滤器就足够了,这样您就不需要
定义,但只是按所需顺序的
定义.
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>
如果您想将 URL 模式保留在 @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 {}
但是您仍然应该将
保留在 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 之前,这一切都将失败,因为它会因
而没有
的存在而窒息.另请参阅 使用 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
这篇关于如何使用 WAR 中的注释定义 servlet 过滤器的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!