How to define servlet filter order of execution using annotations in WAR
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.
For example,
@WebFilter(filterName="filter1")
public class Filter1 implements Filter {}
@WebFilter(filterName="filter2")
public class Filter2 implements Filter {}
with in web.xml
just this:
<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>
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 {}
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>
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
The Servlet 3.0 spec doesn't seem to provide a hint on how a container should order filters that have been declared via annotations. It is clear how about how to order filters via their declaration in the web.xml file, though.
Be safe. Use the web.xml file order filters that have interdependencies. Try to make your filters all order independent to minimize the need to use a web.xml file.