🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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 fromjakarta.servletpackage 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/helloendpoint.
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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment