What is OncePerRequestFilter?

Under what circumstances a Filter may possibly be executed more than once per request?

You could have the filter on the filter chain more than once.

The request could be dispatched to a different (or the same) servlet using the request dispatcher.


A common use-case is in Spring Security, where authentication and access control functionality is typically implemented as filters that sit in front of the main application servlets. When a request is dispatched using a request dispatcher, it has to go through the filter chain again (or possibly a different one) before it gets to the servlet that is going to deal with it. The problem is that some of the security filter actions should only be performed once for a request. Hence the need for this filter.


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.