How to Define a Spring Boot Filter

Spring Boot provides powerful mechanisms for processing HTTP requests and responses. One such mechanism is the filter, which allows you to perform operations before or after the request is processed by a controller. Filters can be used for tasks such as logging, authentication, and modifying request/response data.

In this tutorial, we'll explore how to define and configure a filter in a Spring Boot application.

Prerequisites

  • JDK 17 or later
  • Maven or Gradle
  • IDE (IntelliJ IDEA, Eclipse, etc.)

Step 1: Set Up a Spring Boot Project

1.1 Create a New Spring Boot Project

Use Spring Initializr to create a new project with the following dependencies:

  • Spring Web

Download and unzip the project, then open it in your IDE.

1.2 Configure application.properties

Set up the application properties for your project. This step is optional and only needed if you want to configure specific properties for your application.

# application.properties

server.port=8080

Step 2: Define the Filter

A filter in Spring Boot is a component that performs filtering tasks on either the request to a resource, the response from a resource, or both.

2.1 Create a Filter Class

Create a class that implements the javax.servlet.Filter interface. In this example, we'll create a simple logging filter that logs the details of incoming requests and outgoing responses.

package com.example.demo;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;

import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class LoggingFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Initialization logic, if any
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("Incoming request: " + request.getRemoteAddr());
        chain.doFilter(request, response);
        System.out.println("Outgoing response: " + response.getContentType());
    }

    @Override
    public void destroy() {
        // Cleanup logic, if any
    }
}

Explanation:

  • @WebFilter(urlPatterns = "/*"): This annotation declares the class as a filter and specifies that it should be applied to all URL patterns.
  • init(FilterConfig filterConfig): This method is called once when the filter is initialized. It's useful for setup tasks.
  • doFilter(ServletRequest request, ServletResponse response, FilterChain chain): This method is called for every request and response pair. The chain.doFilter(request, response) call passes the request and response to the next filter in the chain or to the target resource if there are no more filters.
  • destroy(): This method is called once when the filter is destroyed. It's useful for cleanup tasks.

2.2 Register the Filter (Optional)

If you prefer not to use the @WebFilter annotation, you can manually register the filter using a FilterRegistrationBean in a configuration class.

package com.example.demo;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean<LoggingFilter> loggingFilter() {
        FilterRegistrationBean<LoggingFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new LoggingFilter());
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }
}

Explanation:

  • @Configuration: Marks the class as a source of bean definitions.
  • FilterRegistrationBean<LoggingFilter>: Registers the LoggingFilter with the application.
  • registrationBean.addUrlPatterns("/*"): Specifies the URL patterns that the filter should apply to.

Step 3: Create a REST Controller

Create a simple REST controller to test the filter.

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

Explanation:

  • @RestController: Marks the class as a REST controller.
  • @GetMapping("/hello"): Maps GET requests to /hello to the hello method.
  • hello(): Returns a simple greeting.

Step 4: Running the Application

4.1 Run the Application

Run the Spring Boot application. You can do this from your IDE or by using the command line:

./mvnw spring-boot:run

4.2 Testing the Filter

Open your browser and navigate to http://localhost:8080/hello. You should see the following output in your browser:

Hello, World!

Check the console output of your application. You should see logs from the LoggingFilter:

Incoming request: 0:0:0:0:0:0:0:1
Outgoing response: text/plain;charset=UTF-8

Conclusion

In this tutorial, you have learned how to define and configure a filter in a Spring Boot application. Filters allow you to perform operations on incoming requests and outgoing responses, making them useful for tasks such as logging, authentication, and modifying request/response data. By using either the @WebFilter annotation or manual registration with a FilterRegistrationBean, you can easily integrate filters into your Spring Boot application.


Comments