DEV Community

Salad Lam
Salad Lam

Posted on

Default Servlet filter loaded by Spring Boot

Notice

I wrote this article and was originally published on Qiita on 4 September 2021.


What is servlet filter

You can get the answer from here.

How Spring Boot creates and loads filter

First creates bean which implements javax.servlet.Filter interface (Normally filter bean is extended from org.springframework.web.filter.GenericFilterBean class). Below is an example

public class HttpEncodingAutoConfiguration {
    //...

    @Bean
    @ConditionalOnMissingBean
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(this.properties.getCharset().name());
        filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));
        return filter;
    }

    // ...
}
Enter fullscreen mode Exit fullscreen mode

Then during Servlet registrate to servlet container (Servlet class is org.springframework.web.servlet.DispatcherServlet), beans created above will be collected and registered at

public class ServletContextInitializerBeans extends AbstractCollection<ServletContextInitializer> {
    // ...

    @SuppressWarnings("unchecked")
    protected void addAdaptableBeans(ListableBeanFactory beanFactory) {
        MultipartConfigElement multipartConfig = getMultipartConfig(beanFactory);
        addAsRegistrationBean(beanFactory, Servlet.class, new ServletRegistrationBeanAdapter(multipartConfig));
        // *** HERE ***
        addAsRegistrationBean(beanFactory, Filter.class, new FilterRegistrationBeanAdapter());
        for (Class<?> listenerType : ServletListenerRegistrationBean.getSupportedTypes()) {
            addAsRegistrationBean(beanFactory, EventListener.class, (Class<EventListener>) listenerType,
                    new ServletListenerRegistrationBeanAdapter());
        }
    }

    // ...
}
Enter fullscreen mode Exit fullscreen mode

Filter registered by default

Filter Function
org.springframework.security.web.FilterChainProxy Used by Spring Security. It holds many sub-filter for performing security policy
org.springframework.boot.web.servlet.filter.OrderedRequestContextFilter Exposes the request object to the current thread
org.springframework.boot.web.servlet.filter.OrderedHiddenHttpMethodFilter Converts posted method parameters into HTTP methods
org.springframework.boot.web.servlet.filter.OrderedFormContentFilter Parses form data for HTTP PUT, PATCH, and DELETE requests and exposes it as Servlet request parameters. By default the Servlet spec only requires this for HTTP POST
org.springframework.boot.web.servlet.filter.OrderedCharacterEncodingFilter apply default character encoding for request if not specify in request

Top comments (0)