Suppose I have following in my web.xml
<filter-mapping> <filter-name>F1</filter-name> <url-pattern>/XYZ/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>F2</filter-name> <url-pattern>/XYZ/abc.do</url-pattern> </filter-mapping> <filter-mapping> <filter-name>F3</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
What will be the order in which the filters will be called if a request comes as /XYZ/abc.do and why?
The order the container uses in building the chain of filters to be applied for a particular request URI is as follows: First, the <url-pattern> matching filter mappings in the same order that these elements appear in the deployment descriptor.
xml determines the order in which the web container applies the filter to the servlet. To reverse the order of the filter, you just need to reverse the filter-mapping elements in the web. xml file.
In the order their mappings are defined in web.xml
If using annotations (@WebFilter
) the order seems to be undefined - you still have to declare the <filter-mapping>
entries in web.xml.
Section 6.2.4 of the Servlet specification 3.0:
When processing a
<filter-mapping>
element using the<url-pattern>
style, the container must determine whether the<url-pattern>
matches the request URI using the path mapping rules defined in Chapter 12, “Mapping Requests to Servlets”.The order the container uses in building the chain of filters to be applied for a particular request URI is as follows:
First, the
<url-pattern>
matching filter mappings in the same order that these elements appear in the deployment descriptor.Next, the
<servlet-name>
matching filter mappings in the same order that these elements appear in the deployment descriptor.If a filter mapping contains both
<servlet-name>
and<url-pattern>
, the container must expand the filter mapping into multiple filter mappings (one for each<servlet-name>
and<url-pattern>
), preserving the order of the<servlet-name>
and<url-pattern>
elements.
In short: they're applied in the order in which they appear in the XML file. It gets interesting if you hit an URL that's covered by both <url-pattern>
and <servlet-name>
bound filters, because then all URL-pattern bound filters are applied before all servlet-name bound filters. I've never been in this situation (haven't seen any servlet-name bound filters at all), but I reckon it could be quite confusing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With