Logo

dev-resources.site

for different kinds of informations.

Techniques for Mastering Spring Interceptors: Detailed Guide with Examples

Published at
12/11/2024
Categories
codeproject
spring
springhttpsecurity
Author
anh_trntun_4732cf3d299
Author
22 person written this
anh_trntun_4732cf3d299
open
Techniques for Mastering Spring Interceptors: Detailed Guide with Examples

1. Understanding Spring Interceptors

Spring Interceptors are part of the Spring Web module and are implemented using the HandlerInterceptor interface. They offer a way to intercept HTTP requests before they reach the controller and after the controller has processed the request. This allows you to perform tasks such as logging, authentication, and modifying the request or response.

1.1 What is a Spring Interceptor?

Image

A Spring Interceptor is an object that performs certain actions before and after the execution of a request handler (controller). It allows for pre-processing and post-processing of requests, which can be used for various purposes like modifying requests, handling errors, or adding additional data to the response.

1.2 Key Methods of HandlerInterceptor

Image

The HandlerInterceptor interface includes three primary methods:

  • preHandle(HttpServletRequest request, HttpServletResponse response, Object handler): Called before the actual handler (controller) is executed. It can be used to perform actions such as authentication checks or logging.
  • postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView): Called after the handler has been executed but before the view is rendered. It can be used to modify the model or the view.
  • afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex): Called after the complete request has finished and the view has been rendered. This method is useful for cleanup activities or final logging.

1.3 When to Use Interceptors

Interceptors are ideal for scenarios where you need to apply cross-cutting concerns consistently across multiple handlers. Common use cases include:

  • Logging : Capture and log details of incoming requests and outgoing responses.
  • Authentication and Authorization : Verify user credentials and permissions before processing requests.
  • Performance Monitoring : Measure the time taken to handle requests and responses.

2. Implementing Spring Interceptors

Now, let's walk through the implementation of a Spring Interceptor with code examples. We'll create an interceptor to log request details and measure the time taken to handle requests.

2.1 Creating a Custom Interceptor

First, we'll define a custom interceptor class that implements the HandlerInterceptor interface.

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Instant;

@Component
public class RequestLoggingInterceptor implements HandlerInterceptor {

    private Instant startTime;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        startTime = Instant.now();
        System.out.println("Incoming request: " + request.getMethod() + " " + request.getRequestURI());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // Can modify the model or view if needed
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Instant endTime = Instant.now();
        long duration = endTime.toEpochMilli() - startTime.toEpochMilli();
        System.out.println("Request completed in " + duration + " ms");
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, preHandle logs the incoming request, and afterCompletion logs the time taken to process the request.

2.2 Configuring the Interceptor

Next, we need to register the interceptor in the Spring configuration.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private RequestLoggingInterceptor requestLoggingInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(requestLoggingInterceptor);
    }
}
Enter fullscreen mode Exit fullscreen mode

This configuration ensures that the RequestLoggingInterceptor is applied to all incoming requests.

3. Testing and Results

To see the interceptor in action, you can run your Spring Boot application and make some HTTP requests. For example, sending a request to a controller endpoint will trigger the interceptor methods, and you should see log outputs similar to the following:

Incoming request: GET /api/example
Request completed in 123 ms
Enter fullscreen mode Exit fullscreen mode

This output indicates that the interceptor is correctly logging the request details and measuring the request processing time.

4. Conclusion

Spring Interceptors are a versatile and powerful tool for handling cross-cutting concerns in your web applications. By implementing and configuring interceptors, you can manage logging, authentication, performance monitoring, and more with ease. If you have any questions or need further clarification on Spring Interceptors, feel free to leave a comment below!

Read posts more at : Techniques for Mastering Spring Interceptors: Detailed Guide with Examples

spring Article's
30 articles in total
Favicon
Launched a Web version of my Project using Java Spring Framework, Spring Boot Web
Favicon
Developing a project using Java Spring Framework, JSON, JPA and PostgreSQL
Favicon
Волшебные скоупы: Как Spring организует работу бинов
Favicon
Quando usar ResponseEntity?
Favicon
What is load balancing and how to do it on client side
Favicon
Capturing and Testing Logs in Java with SLF4J and Logback: A Simple Guide
Favicon
Can you find the Output of this Java Code
Favicon
Ways to Speed Up Spring Boot Application Startup Time
Favicon
Apache wicket with spring boot example application: notice board
Favicon
Handling the "Forwarded" Header in Spring Boot Applications
Favicon
About UriComponentsBuilder and UriComponents
Favicon
Spring Boot: About @SpringBootApplication
Favicon
Spring Security: CSRF protection
Favicon
ISBN Stacks — A look at a possible Spring Application implementation without annotations
Favicon
spring profiles dev production
Favicon
Learn Spring Data JPA, Part - 1
Favicon
Methods for Efficient Large File Processing in Spring Boot
Favicon
Hexagonal Architecture — A Favorite Lyrics Spring Boot — Java Example
Favicon
Validation in Spring REST Framework (SRF)
Favicon
spring
Favicon
Spring Security: Redirect to login page if access pages which is for authorized user only
Favicon
Lambda vs. Named Functions: Choosing the Right Tool for the Job
Favicon
Techniques for Mastering Spring Interceptors: Detailed Guide with Examples
Favicon
Techniques for Using @NoRepositoryBean in Spring Data JPA: A Comprehensive Guide
Favicon
Understanding the Spring Framework: A Developer’s Journey to Clean Code 🚀
Favicon
@PreConstruct and @PostConstruct annotation Spring Boot Example
Favicon
Java’s Functional Programming: the OOP influence
Favicon
🧪 Тестирование с TestRestTemplate и MockMvc: миссия "Котики против багов" 🐞
Favicon
spring boot
Favicon
Reasons to Use WireMock for Testing REST APIs in Spring Boot Applications

Featured ones: