19

Is it possible to use two filters that have the same url-mapping?

<filter>
 <filter-name>TeeFilter</filter-name>
 <filter-class>filter1r</filter-class>
</filter>
<filter-mapping>
 <filter-name>TeeFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<display-name>CredentialsFilter</display-name>
<filter-name>CredentialsFilter</filter-name>
<filter-class>filter2</filter-class>
</filter>
<filter-mapping>
 <filter-name>CredentialsFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
mosaad
  • 2,276
  • 5
  • 27
  • 49

2 Answers2

21

Yes. You can.

The order you placed in web.xml will execute.

So here,

First control goes to TeeFilter and then to CredentialsFilter.

And if you want to execute CredentialsFilter first, change the order in web.xml

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • I was only working with CredentialsFilter and once I added the TeeFilter which is just a logback logger for logging http requests and responses, some of the services stopped working and others are still working. Do you have any idea why would this happen? – mosaad Nov 15 '13 at 11:04
  • @mosaad Yes, That's really weird. It should not happen. Do you observer the order of execution? and any exceptions ? – Suresh Atta Nov 15 '13 at 11:15
  • order of execution does not make a difference and the log file created says that a 204 Response was received – mosaad Nov 15 '13 at 13:17
  • 3
    old question missing an important point: you need a chain.doFilter(request, response); in your public void doFilter(...) – Squizer Jun 15 '17 at 14:24
2

When using annotation ,it seems like it compares the two filters lexicographically.And then choose the one that comes first according to this comparison. Example I tried with two filters named Filter1.java and Filter2.java.Both filters have the same url-mapping. When I invoke the mapped url,Filter1.java executes first.But When I rename Filter1.java to Filter3.java. Then Filter2.java executes first. To be more clear. If you have 2 filters A and B.When using annotation to map the same url,A will always execute first. Can you try if you can achieve this result like me.Thanks.If not let me know

  • If you are using annotations from spring I believe @Order may be used to override the lexical order. This answer is a good addition to the original question. – Joeblade Feb 18 '22 at 12:17