GenericFilterBean vs OncePerRequestFilter when to use each?

Bogdan Emil Mariesan picture Bogdan Emil Mariesan · May 18, 2018 · Viewed 8.3k times · Source

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.

  1. For a JWT filter which implementation should be used and why?
  2. For a CORS filter which implementation should be used and why? etc.

Answer

Kayaman picture Kayaman · May 18, 2018

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.