Introduction

Spring Boot provides a powerful way to intercept HTTP requests and responses using Interceptors. Interceptors act as middleware that allows developers to modify incoming requests or outgoing responses before they reach the controller or after processing. They are useful for logging, authentication, authorization, request validation, and more.

In this article, we will explore what interceptors are, their benefits, and how to implement them in a Spring Boot application.


What Are Interceptors in Spring Boot?

Interceptors in Spring Boot are classes that implement the HandlerInterceptor interface. They allow pre-processing and post-processing of HTTP requests handled by controllers. The interceptor mechanism follows a three-step execution process:

  1. preHandle() – Executed before the request reaches the controller.
  2. postHandle() – Executed after the controller processes the request but before the response is sent.
  3. afterCompletion() – Executed after the complete request has been processed.

Why Use Interceptors?

Interceptors are useful for:

  • Logging requests and responses for debugging and auditing purposes.
  • Authentication and authorization to secure endpoints.
  • Modifying request headers or body before they reach the controller.
  • Performance monitoring by calculating request processing time.
  • Data transformation before sending responses to clients.

Implementing Interceptors in Spring Boot

Step 1: Create a Custom Interceptor

To create an interceptor, implement HandlerInterceptor and override its methods.

import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggingInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        logger.info("Incoming Request: {} {}", request.getMethod(), request.getRequestURI());
        return true; // Proceed with the request
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        logger.info("Response Status: {}", response.getStatus());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        logger.info("Request Completed");
    }
}

Step 2: Register the Interceptor

Once the interceptor is created, register it using a WebMvcConfigurer class.

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 {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoggingInterceptor());
    }
}

Step 3: Testing the Interceptor

Start your Spring Boot application and make an HTTP request. You should see the logs generated by the interceptor.


Advanced Interceptor Features

1. Excluding Specific Endpoints

You can exclude certain paths from being intercepted.

registry.addInterceptor(new LoggingInterceptor())
        .excludePathPatterns("/health", "/metrics");

2. Chaining Multiple Interceptors

You can register multiple interceptors in a specific order.

registry.addInterceptor(new AuthInterceptor());
registry.addInterceptor(new LoggingInterceptor());

3. Using @Component for Dependency Injection

Instead of manually instantiating interceptors, you can use @Component annotation and inject dependencies.

@Component
public class LoggingInterceptor implements HandlerInterceptor {
    // Inject dependencies here
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private LoggingInterceptor loggingInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loggingInterceptor);
    }
}

External Links


FAQs

1. What is the purpose of an interceptor in Spring Boot?

Interceptors act as middleware that can pre-process and post-process HTTP requests before they reach the controller or after processing.

2. How is an interceptor different from a filter?

Filters operate at a lower level and can modify requests/responses before they reach Spring MVC, whereas interceptors work within Spring MVC and focus on controller logic.

3. Can we modify request parameters in an interceptor?

Yes, you can modify request attributes but not directly modify the request body in an interceptor.

4. How do I handle exceptions in an interceptor?

You can handle exceptions in the afterCompletion() method by checking if an exception is present.

5. Can interceptors be used for authentication?

Yes, interceptors are often used for authentication and authorization by validating user sessions before requests reach the controller.

6. Can multiple interceptors be used in a Spring Boot application?

Yes, you can register multiple interceptors, and they will execute in the order they are registered.

7. How do I exclude certain endpoints from being intercepted?

Use .excludePathPatterns("/path") while registering the interceptor to exclude specific endpoints.

8. Can interceptors be used for logging?

Yes, interceptors are widely used for logging HTTP requests and responses.

9. Is there an annotation-based way to create interceptors?

No, Spring MVC interceptors require implementing HandlerInterceptor and registering it via WebMvcConfigurer.

10. Can interceptors modify HTTP response headers?

Yes, interceptors can modify response headers before the response is sent to the client.


Conclusion

Spring Boot interceptors are a powerful way to manage HTTP requests and responses. They are useful for tasks such as logging, authentication, and request modification. By implementing interceptors effectively, developers can enhance application security and performance.