Reputation: 1346
As the documentation say:
Filter base class that aims to guarantee a single execution per request dispatch, on any servlet container.
There's a question What is OncePerRequestFilter? I still don't know why we use it.
It says "on any servlet container". It means that there are servlet containers will execute the filter more than once?
Upvotes: 5
Views: 12266
Reputation: 19
The javadoc for OncePerRequestFilter states
As of Servlet 3.0, a filter may be invoked as part of a javax.servlet.DispatcherType REQUEST or javax.servlet.DispatcherType ASYNC dispatches that occur in separate threads. A filter can be configured in web.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 method shouldNotFilterAsyncDispatch() 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 in web.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.
Upvotes: -2
Reputation: 654
I have answered it here also. To understand the role of OncePerRequestFilter, we need to first clearly understand how a normal filter behaves. When you want some specific code to execute just before or after servlet execution, you create a filter which works as:
code1 ===> servlet execution (using chain.doFilter()) ===> code2
So code1 executes before servlet and code2 after servlet execution. But here, while servlet execution, there can be some other request to a different servlet and that different servlet is also having this same filter. In this case, this filter will execute again.
OncePerRequestFilter prevents this behavior. For our one request, this filter will execute exactly one time (no more no less). This behavior is very useful while working with security authentication.
Upvotes: 6
Reputation: 3503
One use case is to write your own custom filter which extends the OncePerRequestFilter.
This ensures that your custom filter is on the frontline when the requests come in and and the specification ensures that it is executed.
Hope that helps.
Upvotes: 1