Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will be the order in which filters will be called? [duplicate]

Tags:

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?

like image 278
Xyzxyz Xyz Avatar asked Oct 29 '11 09:10

Xyzxyz Xyz


People also ask

How to order filters in Java?

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.

Which element of Web XML defines the order in which filters are called?

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.


2 Answers

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.

like image 144
Bozho Avatar answered Dec 03 '22 06:12

Bozho


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:

  1. First, the <url-pattern> matching filter mappings in the same order that these elements appear in the deployment descriptor.

  2. 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.

like image 33
Barend Avatar answered Dec 03 '22 06:12

Barend