Spring Boot - Servlet Filter
Last Updated :
26 Nov, 2023
Spring boot Servlet Filter is a component used to intercept & manipulate HTTP requests and responses. Servlet filters help in performing pre-processing & post-processing tasks such as:
- Logging and Auditing: Logging operations can be performed by the servlet filter logging the request and response which assists in debugging and troubleshooting.
- Authentication and Authorization: Authentication and Authorization refer to the process of providing access and checking if a user has certain privilege permissions to access a resource
- Caching: Caching is a mechanism that allows us to store data temporarily for faster access in the future. It can be done by caching response in servlet filters.
- Routing: Servlet filters can also be used for routing responses to different controllers giving us more control over handling requests
Example of Servlet Filter
Let us discuss some Real-Life examples to better understand the Spring Boot Servlet Filter.
1. Food Ordering: While ordering food on online platforms, a user may give specific cooking instructions like excluding onion or any other substance that a user may be allergic to.
So, this request made by the user will first go through a different procedure - Excluding onions while cooking their food. This same procedure will be applied to all the users who make similar requests. You can think of this procedure as a FILTER for these types of requests.
2. E-Commerce website: It offers bulky discounts when products are purchased in the given time span. So, all the requests made by clients will be applied to a filter of discounts during this time span!
Servlet Filter - Real-World ExampleIn the above diagrams, we are applying a servlet filter for all those requests with a time stamp between 12:00 and 13:00. If a request is made by a client anywhere all over the world in this time span, it will go through this filter and be given high discounts.
- All the requests made before or after this timestamp will be treated as normal requests and won't go through a filter.
Spring boot is an extension of the Spring framework & has an inbuilt mechanism for implementing servlet filters easily by using @Component Annotation. Furthermore, if we have more than one filter in our application then we can set the order using @Order annotation to set the execution order of servlet filters.
Here's the order of execution of the Servlet Filter :
Servlet Filter - RequestNow, while working with Custom Servlet filters, we will require the following classes and interfaces in our code in spring boot :
- Filter - Interface that our custom filter class must implement
- FilterRegistrationBean - This bean registers our Custom Servlet Filter with the spring context. This allows us to configure the servlet filter for our specific needs such as -
- URL Patterns
- Dispatcher type
- Invocation etc.
However, this one is optional in some cases
Types of Servlet Filters
There are mainly two types of servlet filters:
- Pre-Built Servlet Filter: Pre-built servlet Filters are a convenient and efficient way to implement a specific functionality such as
- authentication - Authentication Filter
- logging - CommonsRequestLoggingFilter
- authorization filter - FilterSecurityInterceptor
- These are some of the pre-built servlet filters provided by Spring Boot, that save us the time and effort of writing a customized filter.
- However, depending on our requirements we may need to implement a filter specific to our needs that's where Custom Filters are.
- Custom Filters: Custom filters based on our specific needs can be implemented by implementing the Filter Interface.
In this article, we'll be exploring how to build a custom servlet filter.
Step-By-Step Implementation
Step 1: Go to spring Initializr and create a configuration file with the following dependency :
Configuration FileStep 2: Extract the zip file, and go to your favorite IDE, we'll use Intellij in this article
Step 3: Now create two packages - Filter and REST, and further two classes in them - MyFilter and ServletController (appropriately). Your final directory structure should look something like this:-
Directory StructureSettings file for our Spring Boot Project i.e. pom.xml
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.GeeksForGeeks</groupId>
<artifactId>ServletFilterExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ServletFilterExample</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Step 4: Implementing the Filter. Write the following business logic in the class - MyFilter.
Servlet Filter
In the following example, we've defined a custom filter. This custom Filter is annotated with @Component so that it can be recognized by spring context. And overrides the doFilter() method that takes 3 parameters -
- ServletRequest
- ServletResponse
- FilterChain
Java
//Implementation layer to implement Filter
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import java.io.IOException;
import org.springframework.stereotype.Component;
// Servlet Filter Class
@Component
public class MyFilter implements Filter {
// doFilter() Method - To apply Filter's Business logic.
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain filterChain)
throws IOException, ServletException{
System.out.println("This is a Servlet doFilter() Method !");
// Get remote data
System.out.println("Remote Host : "+ servletRequest.getRemoteHost());
System.out.println("Remote Address : "+ servletRequest.getRemoteAddr());
// Invoke filterChain to execute the next filter inorder.
filterChain.doFilter(servletRequest,servletResponse);
}
}
Code Explanation:
- The doFilter() method is invoked for every request that comes to our controller.
- And we've simply printed the remote data in this method
- filterChain is a crucial component in this, we must call this method, or else our request will never reach the desired controller. This is important because this method will execute the next filter according to the specified order.
For example, if we've added 3 filters annotated with @Order Annotation, then they will be executed in order and chained by this method
Step 5: Create a simple REST API endpoint inside the REST package.
Rest Controller
We've defined a simple rest controller for demo purposes. By default, our Fitler can recognize any URL pattern so we don't have to worry about mapping in this example. However, if we need the filter to be invoked only for specific URLs, then we need to specify that before which we will see in the next example.
Java
// Simple REST Controller for testing our Servlet Filter
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class ServletController {
//Get-Request Mapping
@GetMapping("/")
public String hello(){
return "This is a sample API for testing Servlet Filter - Spring Boot!";
}
}
Output:
Web-Browser OutputConsole Output:
Console OutputOther ways we can use servlet filters involve -
- For a category of URL Patterns
- Multiple servlet filters chained with @Order annotation and many more.
Servlet filters with a specific or group of URL Patterns
Servlet filters are by default configured to be executed for every URL pattern but they can also be applied only to a group of controllers, we can choose which controller/requests will be applied to a certain filter. For example, when a user is logging in, we can apply an authorization filter for /login endpoint.
We will require a FilterRegistrationBean to restrict a Servlet Filter to specific URL Patterns. Then inside it, we can specify the URL pattern it is to be applied to, and its order of execution and we can configure it in any way we want.
Java
//Bean for AuthorizationFilter
@Bean
public FilterRegistrationBean<AuthorizationFilter> filterRegistrationBean() {
// Filter Registration Bean
FilterRegistrationBean<AuthorizationFilter> registrationBean = new FilterRegistrationBean();
// Configure Authorization Filter
registrationBean.setFilter(new AuthorizationFilter());
// Specify URL Pattern
registrationBean.addUrlPatterns("/login/*");
// Set the Execution Order of Filter
registrationBean.setOrder(2);
return registrationBean;
}
Multiple Servlet Filter Ordering
We can specify the order of execution of servlet filters in the Deployment Descriptor. However, in Spring Boot, we can do it in a much easier way by using @Order Annotation.
Java
//Methods with Annotation for Multiple-Filter
// Authorization Filter (1st Filter)
// Executed 1st
@Order(1)
@Component
public class AuthorizationFilter implements Filter {
// Code for 1st Filter
}
// Logging Filter (2nd Filter)
// Executed 2nd
@Order(2)
@Component
public class LoggingFilter implements Filter {
// Code for 2nd Filter
}
// Debug Filter (3rd Filter)
// Executed 3rd
@Order(3)
@Component
public class DebugFilter implements Filter {
// Code for 3rd Filter
}
The above code demonstrates how the ordering of filters can be specified easily in Spring Boot using @Order Annotation.
- The AuthorizationFilter will execute first, then filterChain.doFilter() method will call the next filter that is, LoggingFilter, and so on until all the filters are executed in a chained fashion.
Order of ExecutionConclusion
Spring boot Servlet filter is a powerful tool to intercept and manipulate requests and responses. It helps in implementing various functionalities such as authentication, logging, debugging, etc.
- Spring Boot - Servlet Filter is easy to implement, the core interface required here is the filter interface.
- @Component and @Bean annotations help us implement Servlet Filters according to our specific needs.
- Filter Chaining and order of executions are a core mechanism that builds the foundation of servlets and help us perform pre and post-processing operations on requests and responses.
- Another real-world example - Let's say a user is logging in to our application for the first time. Then, they will be offered a special discount for premium access. This premium access discount is given through a servlet filter noting the login count of the user.
Similar Reads
Spring Boot - REST Example
In modern web development, most applications follow the Client-Server Architecture. The Client (frontend) interacts with the server (backend) to fetch or save data. This communication happens using the HTTP protocol. On the server, we expose a bunch of services that are accessible via the HTTP proto
4 min read
Servlet - Filter
A filter is an object that is used throughout the pre-and post-processing stages of a request. Filters are mostly used for filtering tasks such as server-side logging, authentication, and authorization, input validation, and so on. The servlet is pluggable, which means that the entry is specified in
3 min read
Working of Servlet
A Servlet is an instance of a class that implements javax.servlet.Servlet. Most Servlets, however, are extended to one of the standard implementations of that interface, as it namely javax.servlet.GenericServlet and the javax.servlet.http.HttpServlet. Developers use this as a blueprint when crafting
6 min read
Spring Boot - Admin Server
Spring boot is one of the most popular applications to develop Java enterprise applications. When you have so many components in your application, you need to monitor and manage them. You have multiple spring boot applications running you need an admin for monitoring. Spring boot admin provides you
4 min read
Spring - REST Controller
Spring Boot is built on top of the Spring and contains all the features of spring. Spring Boot is a popular framework for building microservices and RESTful APIs due to its rapid setup and minimal configuration requirements. When developing REST APIs in Spring, the @RestController annotation plays a
3 min read
Servlet - War File
A war (web archive) A web project's files are contained in this file. It may contain files such as servlet, xml, jsp, image, html, css, and js. Here, we'll go through what a war file is, how to make one, how to deploy one, and how to remove one. What is WAR File? The WAR file (Web Application Resour
2 min read
Angular PrimeNG FilterService Component
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. It provides a lot of templates, components, theme design, an extensive icon library, and much more.
7 min read
Get the Response Body in Spring Boot Filter
In a Spring Boot application, filters can be used to intercept requests and responses, allowing you to manipulate them before reaching the controller or after the response is generated. A common requirement is capturing or logging the response body in the Spring Boot filter, especially for monitorin
5 min read
How to Define a Spring Boot Filter?
A filter in Spring Boot intercepts HTTP requests and responses in the web application. Filters allow developers to perform operations before or after a request is processed by the controller or servlet. They are useful for authentication, logging, request modification, and more tasks. Spring Boot si
7 min read
Java Servlet Filter
Filters are part of Servlet API Since 2.3. Like a Servlet, a filter object is instantiated and managed by the Container and follows a life cycle that is similar to that of a Servlet. A Servlet has 4 stages as depicted below Instantiate.Initialize.Filter.destroy. These stages are similar to a servlet
4 min read