Spring Boot Web Filter

Farzin Pashaee
3 min readMay 7, 2022

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

--

--

Farzin Pashaee

Software Engineer at Maybank, AI and ML enthusiastic