arrow-rightgithublinkedinscroll-to-topzig-zag

How do Filters work in Spring Boot?

Last Updated On

Watch on YouTube

Filter is a java class which is executed for each incoming request and outgoing response. This fact makes it a perfect place to put logic that will be performed on the request before it reaches the Spring Framework and on the response before it reaches the client. This is why filters are a very popular place to put security checks such as authorization and authentication, implement login, and also put a centralized code which otherwise may have been duplicated in the different parts of the controller.

It's worth noting that filters are a web servlet container concept. They can be applicable to any application that runs in a web container such as Tomcat, JBoss, or undertow. To better understand where filters are placed relative to other Spring Framework elements, let's take a look at the following diagram.

A common scenario is when a client sends requests to a web server. Our web server most likely is going to be represented by a container such as Tomcat. Tomcat then forwards this request to a "Dispatcher Servlet" for processing. The "Dispatcher Servlet" then sends this request to a controller with the help of the "Handler Mapping Interface" to execute business logic. Once everything is done, the controller sends a response to the client:

A filter sits right in between a web container and the dispatcher servlet:

In fact, most of the time, we're going to work with multiple filters. A collection of filters is called "Filter Chain":

In the real world, it's not that uncommon to see multiple "Filter Chains". It's worth mentioning that any filter can decide to block a request from following down the chain and return early.

In conclusion, filters are an essential part of the Spring Framework, providing a powerful mechanism for controlling the flow of requests and responses. They are executed for each incoming request and outgoing response, making them a perfect place to put security checks, implement login, and put centralized code. With the help of filters, developers can easily add robust security and other functionalities to their applications, without duplicating code in different parts of the controller.