I've already found some questions related to this topic but I've realised that none of them shed light on this topic.
Apparently the OncePerRequestFilter ensures that a request passes through the filter only once in the filter chain, but it's not exactly clear to me when the opposite would happen.
It would be nice to see some scenarios in which to use one or the other. Also an example on when and how the filter might be applied several times on the filter chain.
For e.g.
The javadoc for OncePerRequestFilter
states
As of Servlet 3.0, a filter may be invoked as part of a
javax.servlet.DispatcherType REQUEST
orjavax.servlet.DispatcherType ASYNC
dispatches that occur in separate threads. A filter can be configured inweb.xml
whether it should be involved in async dispatches. However, in some cases servlet containers assume different default configuration. Therefore sub-classes can override the methodshouldNotFilterAsyncDispatch()
to declare statically if they should indeed be invoked, once, during both types of dispatches in order to provide thread initialization, logging, security, and so on. This mechanism complements and does not replace the need to configure a filter inweb.xml
with dispatcher types.
So it's an additional "safety" feature implemented in Spring to make sure things work the same regardless of the environment. If you look at the classes that extend it, you'll notice there are lots; including CorsFilter
. Not sure if there are Spring filters that don't extend it, probably not.