Spring Boot Web Filter

A Filter in the Spring Boot application is a solution used to intercept the HTTP requests and responses of your application. Filter helps us to perform two operations Before sending the request to the Dispatcher and Before sending a response to the client.

Filters are also like pointcuts in Aspect-Oriented Programming. They are easy to implement and simple to plug in and out from HTTP request processing. Filters can be used for different well-known use cases like Logging, Authentication and Security, Transaction and request manipulation, and…

Filter Interface

In order to implement your custom filter in your application, you need to implement the Filter interface. This interface has 3 methods that needed to be implemented and they will be called in different stages of the filter’s lifecycle.

init

This method will be run when the filter is created and it provides an instance of FilterConfig.

@Override
public void init(FilterConfig filterconfig)
throws ServletException {}

doFilter

This is the main method that helps to intercept the Servlet request process. using FilterChain you can control the next step of the incoming request by calling the next filter in the chain or breaking it.

@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain filterchain)
throws IOException, ServletException {}

destroy

As the name of the method speaks for itself this one will be called when the filter is destroyed for any reason.

@Override
public void destroy() {}

Spring Boot Example

Imagine that you need to have the response time of the request logged in your application for performance evaluation and debugging purposes. You can use the Filter interface to achieve that simply.

Filter Implementation

Using the following implementation you will be able to log the response time.

@Slf4j
@Component
@Order(1)
public class LoggingFilter implements Filter {

@Override
public void init(FilterConfig filterconfig)
throws ServletException {
log.info( filterconfig.getFilterName() + " created" );
}

@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain filterchain)
throws IOException, ServletException {

UUID uuid = UUID.randomUUID();
Long start = System.currentTimeMillis();
request.setAttribute("request-id" , uuid);
log.info( "{} - remote host {}" , uuid , request.getRemoteHost() );
filterchain.doFilter(request, response);
log.info( "{} - response in {}ms",
uuid,
System.currentTimeMillis() - start );
}

@Override
public void destroy() {
log.info( "LoggingFilter destroyed" );
}

}

By having @Component annotation on the class that implemented the Filter interface, that filter class will automatically apply to all incoming requests.

@Component
@Order(2)
public class AuthenticationFilter implements Filter {
....
}

The @Order annotation also can b used to manage the order of filters in a chain of filters.

FilterRegistrationBean

If you need to limit the filter to apply to some specific path and not all incoming requests you can use the FilterRegistrationBean as follow:

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Bean
public FilterRegistrationBean<HeaderProcessFilter> headerProcessFilter(){
FilterRegistrationBean<HeaderProcessFilter> registrationBean
= new FilterRegistrationBean<>();
registrationBean.setFilter(new HeaderProcessFilter());
registrationBean.addUrlPatterns("/student/*");
registrationBean.setOrder(3);
return registrationBean;
}

}

As you can see in the sample FilterRegistrationBean provides the proper methods to set the URL pattern and the order for the filter. The log for the following code will look like this:

... loggingFilter created
... Tomcat started on port(s): 8080 (http) with context path ''
... Started WebMvcFilterApplication in 3.147 seconds (JVM running for 4.724)
... Initializing Spring DispatcherServlet 'dispatcherServlet'
... Initializing Servlet 'dispatcherServlet'
... Completed initialization in 1 ms
... f6e043fd-a6ea-4014-84c3-979cd210eb45 - remote host x.x.x.x
... f6e043fd-a6ea-4014-84c3-979cd210eb45 - authenticating
... f6e043fd-a6ea-4014-84c3-979cd210eb45 - header process
... f6e043fd-a6ea-4014-84c3-979cd210eb45 - response in 118ms

You can find the code for this project on Github.

Hope this article helped you and please support me with your applauding for the story. if you don’t know how it is just like this:

Or buy me a coffee here!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Farzin Pashaee

Farzin Pashaee

Software Engineer at Maybank, AI and ML enthusiastic