Skip to content
Advertisement

What is difference between RequestContextFilter and OncePerRequestFilter in spring?

Spring documentation for Class RequestContextFilter mentions that this filter exposes the request to the current thread, through both LocaleContextHolder and RequestContextHolder.

Can someone please explain how this is different from OncePerRequestFilter class, and how can I implement such a filter?

Advertisement

Answer

You can look at RequestContextFilter source code. It actually extends OncePerRequestFilter and implements the abstract method doFilterInternal to initializes LocaleContextHolder and RequestContextHolder. After this, the Locale and the RequestAttributes can be retrieved anywhere in the current thread.

If you want to declare RequestContextFilter in you app, you can just declare it as a bean :

@Bean 
public RequestContextListener requestContextListener() {
  return new RequestContextListener();
} 

You can also register the filter in the web.xml if you have one.

Advertisement