How to Add Filter in Spring Boot

Filters in Spring Boot are used to intercept HTTP requests and responses to perform various operations like logging, authentication, authorization, etc. In this tutorial, we'll define a custom filter called RequestResponseLoggingFilter to log incoming requests and outgoing responses.

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 file is located in the src/main/resources directory.

# src/main/resources/application.properties

# Server port
server.port=8080

Step 2: Define the RequestResponseLoggingFilter

2.1 Create the Filter Class

Create a new class named RequestResponseLoggingFilter in the com.example.demo.filter package (create the package if it doesn't exist).

package com.example.demo.filter;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class RequestResponseLoggingFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(RequestResponseLoggingFilter.class);

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

    @Override
    public void doFilter(jakarta.servlet.ServletRequest request, jakarta.servlet.ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        logger.info("Incoming request: {} {}", req.getMethod(), req.getRequestURI());

        chain.doFilter(request, response);

        logger.info("Outgoing response: {}", res.getContentType());
    }

    @Override
    public void destroy() {
        // Cleanup code, if needed
    }
}

Explanation:

  • @Component: Marks the class as a Spring bean so it can be automatically registered.
  • Filter: Interface from jakarta.servlet package to define a filter.
  • doFilter: Method where the filter logic is implemented. It logs incoming requests and outgoing responses.

2.2 Register the Filter (Optional)

By annotating the filter with @Component, it is automatically registered. However, you can also register the filter programmatically if needed.

Option 1: Automatic Registration (via @Component)

The filter will be registered automatically by Spring Boot.

Option 2: Manual Registration

If you prefer manual registration, you can do it in a configuration class.

package com.example.demo.config;

import com.example.demo.filter.RequestResponseLoggingFilter;
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<RequestResponseLoggingFilter> loggingFilter() {
        FilterRegistrationBean<RequestResponseLoggingFilter> registrationBean = new FilterRegistrationBean<>();

        registrationBean.setFilter(new RequestResponseLoggingFilter());
        registrationBean.addUrlPatterns("/api/*");

        return registrationBean;
    }
}

Explanation:

  • FilterRegistrationBean: Used to register the filter programmatically.
  • addUrlPatterns: Specifies the URL patterns to which the filter should be applied.

Step 3: Create a Simple Controller

3.1 Create the HelloController

Create a controller to handle incoming requests.

package com.example.demo.controller;

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

@RestController
public class HelloController {

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

Explanation:

  • @RestController: Marks the class as a REST controller.
  • @GetMapping("/api/hello"): Maps GET requests to the /api/hello endpoint.

Step 4: Running and Testing the Application

4.1 Run the Application

Run the Spring Boot application using your IDE or the command line:

./mvnw spring-boot:run

4.2 Test the Filter

Use a tool like Postman or your web browser to send a GET request to http://localhost:8080/api/hello.

Check the logs to see the request and response logging:

INFO  com.example.demo.filter.RequestResponseLoggingFilter - Incoming request: GET /api/hello
INFO  com.example.demo.filter.RequestResponseLoggingFilter - Outgoing response: text/plain;charset=UTF-8

Conclusion

In this tutorial, you have learned how to define a custom filter in a Spring Boot application using Spring Boot 3.2. We covered:

  • Setting up a Spring Boot project.
  • Creating a custom filter to log incoming requests and outgoing responses.
  • Registering the filter using both automatic and manual methods.
  • Creating a simple controller to test the filter.

By following these steps, you can effectively create and use custom filters in your Spring Boot applications.

Comments