0
votes

I have several Servlet filters which need to execute in order - one after the other. I don't want to declare them in the web.xml file, nor do I want to use the @WebFilter annotation. Instead, I use the ServletContext.addFilter() method.

The question is: are the filters chained in the same order, as the order I have called the addFilter() method? Is this documented somewhere?

I saw this question and the answer: How to define servlet filter order of execution using annotations in WAR but it doesn't cover the programmatic case I have.

2

2 Answers

0
votes

I don't know any definitions of the order of filters that are added with ServletContext.addFilter so I wouldn't expect a special order.

I don't know if you'd call it a code smell but it's possible to add a filter with addFilter and from within the filter call the other filter. This way your code defines the order of these two filters. It's not the finest way, I know, but maybe it can help you.

0
votes

It seems that the filters are added in the order the methods of the ServletContext are called, at least in Tomcat.

If we look at the source code of tomcat 8, there is a class ContextFilterMap (inside StandardContext.java) which preserves an array of filter maps. And there are two methods: add and addBefore which preserve an "insertion point" variable which keeps the order of insertion.