Add a Servlet Filter in a Spring Boot application

dVaffection picture dVaffection · Oct 1, 2014 · Viewed 64.3k times · Source

I'd like to have ETag suport. For this purpose there is a ShallowEtagHeaderFilter which does all the work. How can I add it without declaring it in my web.xml (which actually does not exist, because I somehow got by without it so far)?

P.S. I use Spring Boot 1.1.4

P.P.S. Here's a full solution

package cuenation.api;

import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.ShallowEtagHeaderFilter;

import javax.servlet.DispatcherType;
import java.util.EnumSet;

@Configuration
public class WebConfig {

    @Bean
    public FilterRegistrationBean shallowEtagHeaderFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new ShallowEtagHeaderFilter());
        registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));
        registration.addUrlPatterns("/cue-categories");
        return registration;
    }

}

Answer

Brian Clozel picture Brian Clozel · Oct 2, 2014

When using Spring Boot

As mentioned in the reference documentation, the only step needed is to declare that filter as a Bean in a configuration class, that's it!

@Configuration
public class WebConfig {

  @Bean
  public Filter shallowEtagHeaderFilter() {
    return new ShallowEtagHeaderFilter();
  }
}

When using Spring MVC

You're probably already extending a WebApplicationInitializer. If not, then you should convert your webapp configuration from a web.xml file to a WebApplicationInitializer class.

If your context configuration lives in XML file(s), you can create a class that extends AbstractDispatcherServletInitializer - if using configuration classes, AbstractAnnotationConfigDispatcherServletInitializer is the proper choice.

In any case, you can then add Filter registration:

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

Full examples of code-based Servlet container initialization are available in the Spring reference documentation.