DEV Community

Anh Trần Tuấn
Anh Trần Tuấn

Posted on • Originally published at tuanh.net on

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

Top comments (0)