What will be the order in which the filters will be called?

Suppose I have the 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 the request comes as /XYZ/abc.do. And why?

+8
java java-ee servlets servlet-filters
source share
2 answers

In the order in which they are displayed, they are defined in web.xml

If you use annotations ( @WebFilter ), the order seems undefined - you still need to declare <filter-mapping> entries in web.xml.

+12
source share

Section 6.2.4 Servlet 3.0 Specification :

When processing the <filter-mapping> element using the <url-pattern> style, the container must determine whether the <url-pattern> matches the request URI using the path matching rules defined in Chapter 12, Servlet Mapping Requests.

The order used by the container when creating a filter chain for a specific request URI is as follows:

  • First, matching the matching filter <url-pattern> in the same order in which these elements appear in the deployment descriptor.

  • Next, match the matching filter <servlet-name> in the same order in which these items appear in the deployment descriptor.

If the filter mapping contains both <servlet-name> and <url-pattern> , the container must expand the filter mapping to several filter mappings (one for each <servlet-name> and <url-pattern> ), preserving the order of <servlet-name> and <url-pattern> .

In short: they are applied in the order in which they appear in the XML file. Interestingly, if you click on a URL that is surrounded by filters with the <url-pattern> and <servlet-name> , because then all related URL pattern filters are applied before all related servlet filters. I have never been in this situation (I have never seen any filters bound to servlets), but I think this can be quite confusing.

+14
source share

All Articles