1
votes

As of Servlet 3.0, we can now declare web filters by annotation (@WebFilter)or dynamically (via the ServletContext object).

I know that using the @WebFilter does not allow for specifying the filter order. Similarly I haven't found any way to specify the order when declaring it dynamically via the ServletContext.addFilter() method. I've looked at the FilterRegistration object, but there is nothing there either.

Does that mean that the only way to specify the order of a filter in the filter chain is via web.xml? Is there no other mechanism available? Is this not a significant oversight of Servlet 3.0+?

Where in the chain do filters declared via annotation or via the ServletContext object? At the end of those declared in web.xml? Undefined?

1

1 Answers

5
votes

Does that mean that the only way to specify the order of a filter in the filter chain is via web.xml?

Yes. Check the following sections of the Servlet 3.0 spec:

  • 4.4.2 Programmatically adding and configuring Filters

  • 6.2.4 Configuration of Filters in a Web Application

  • 8.1.2 @WebFilter

The only place where filter ordering is mentioned is in section 6.2.4, which specifies how to do it with web.xml. Ordering is not mentioned in the sections on addFilter() and @WebFilter.

Is there no other mechanism available?

Not in the Servlet 3.0 specification, so no.

Is this not a significant oversight of Servlet 3.0+?

I doubt that the omission is an "oversight". A comment from BalusC is this relevant SO post offers one plausible reason why there is no alternative mechanism: What if your webapp ships with 3rd party libraries which includes a filter? It's hard to tell its order beforehand.

Where in the chain do filters declared via annotation or via the ServletContext object? At the end of those declared in web.xml? Undefined?

The ordering is necessarily undefined since the spec does not address those scenarios.