With WebApplicationInitializer
, I can easily add a filter to the ServletContext
within the onStartup()
method.
How to add a filter with WebMvcConfigurerAdapter
? Do I have to use XML?
ADD 1
To help others understand the Spring Web Configuration more easily, I draw the following illustration.
Now you just need to first understand the rational
behind Spring Web configuration. And then pick up which config class to inherit and which method to override from below.
It's less painful to look it up than to remember so many things.
And a good article on Spring Web Initialization:
http://www.kubrynski.com/2014/01/understanding-spring-web-initialization.html
ADD 2
Based on Tunaki
's reply, I checked the AbstractDispatcherServletInitializer
. The filter registration happens in the following code:
Even I override the green getServletFilters()
method, I still cannot access the Dyanmic
result of the registerServletFilter()
. So how can I configure the filter by addMappingForUrlPatterns()
?
It seems I have to
override the whole registerDispatcherServlet()
method.
WebMvcConfigurer
is an interface that is used to customize the Java-based configuration for Spring MVC enabled via@EnableWebMvc
.WebMvcConfigurerAdapter
is just an adapter providing default empty methods for this interface.It does not configure the
DispatcherServlet
, which is what filters are used by. As such, you can't useWebMvcConfigurer
to configure servlet filters.To easily configure filters, you can inherit from
AbstractDispatcherServletInitializer
and overridegetServletFilters()
:If you want to further configure a filter, you will have to override
onStartup
instead:You can access the Dyanmic result of the
registerServletFilter()
as follows in your app config (specifically, WebApplicationInitializer):You can create spring beans that implements Filter and @Inject ServletContext inside of them. Then in a @PostConstruct method, you can register them with servletContext.addServlet("myFilter",this);
The bean must not be declared in the rootContext that is initialised with ContextLoaderListener(rootContext) because the servlet 3.0 api forbids using dynamic registration for the listeners. So it must be declared in the dispatcherContext that is given to DispatcherServlet(dispatcherContext )
spring doc