Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a Filter with WebMvcConfigurerAdapter in Spring?

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.

enter image description here

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:

enter image description here

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.

like image 732
smwikipedia Avatar asked Nov 01 '15 15:11

smwikipedia


People also ask

How do I add a filter to my Spring boot?

There are three ways to add your filter, Annotate your filter with one of the Spring stereotypes such as @Component. Register a @Bean with Filter type in Spring @Configuration. Register a @Bean with FilterRegistrationBean type in Spring @Configuration.

How do I create a custom filter in Spring?

There are a couple of possible methods: addFilterBefore(filter, class) adds a filter before the position of the specified filter class. addFilterAfter(filter, class) adds a filter after the position of the specified filter class. addFilterAt(filter, class) adds a filter at the location of the specified filter class.

How do I register multiple filters in Spring boot?

Add the annotation @ServletComponentScan to the spring boot main class, which will scan all servlet-related classes in the spring boot application context. You can use the url pattern to limit request control based on the request url. If you add multiple filters in a sequence, they will all run one at a time.


2 Answers

You can access the Dyanmic result of the registerServletFilter() as follows in your app config (specifically, WebApplicationInitializer):

@Override
public void onStartup(ServletContext servletContext) throws ServletException {

    // Create the 'root' Spring application context
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();

    rootContext.register(
        AppConfig.class,
        SecurityConfiguration.class,
        HibernateConfiguration.class 
    );

    // Add cuatom filters to servletContext
    FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("recaptchaResponseFilter", new RecaptchaResponseFilter());
    filterRegistration.setInitParameter("encoding", "UTF-8");
    filterRegistration.setInitParameter("forceEncoding", "true");
    filterRegistration.addMappingForUrlPatterns(null, true, "/*");

    // Create the dispatcher servlet's Spring application context
    AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
    dispatcherServlet.register(MVCConfig.class);

    // Register and map the dispatcher servlet
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
like image 130
Psypher Avatar answered Sep 27 '22 18:09

Psypher


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 use WebMvcConfigurer to configure servlet filters.

To easily configure filters, you can inherit from AbstractDispatcherServletInitializer and override getServletFilters():

public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {

    @Override
    protected Filter[] getServletFilters() {
        return new Filter[] { new CharacterEncodingFilter() };
    }

}

If you want to further configure a filter, you will have to override onStartup instead:

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    super.onStartup(servletContext);
    servletContext.addFilter("name", CharacterEncodingFilter.class)
                  .addMappingForUrlPatterns(null, false, "/*");
}
like image 35
Tunaki Avatar answered Sep 27 '22 18:09

Tunaki