Sitemap
DevOps.dev

Devops.dev is a community of DevOps enthusiasts sharing insight, stories, and the latest development in the field.

Spring Boot Interceptors

It is all about spring and spring boot interceptors

4 min readJul 17, 2024

--

Check out my detailed video and join our community by subscribing to my channel. Your support means the world to me!

In this video, we’ve covered several key topics:

  1. Creating an Interceptor?
  2. Registering the Interceptor?
  3. Registering Multiple Interceptors?
  4. How to register an Interceptor with a specific URL pattern
Press enter or click to view image in full size

Spring Boot interceptors are a powerful mechanism to intercept HTTP requests and responses in your application.

They are part of the Spring Web MVC framework and allow you to perform operations before and after the processing of a request by a controller.

Creating an Interceptor

Get Java Codeex’s stories in your inbox

Join Medium for free to get updates from this writer.

To create an interceptor, you need to implement the HandlerInterceptor interface or extend the HandlerInterceptorAdapter class.

package com.javacodeex.interceprots;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoggingInterceptor implements HandlerInterceptor {


@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("Request URL: " + request.getRequestURL());
log.info("Request Method: " + request.getMethod());
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// Can log response details here
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception {
// Can log completion details here
log.info("Request Process completed");

}
}
package com.javacodeex.interceprots;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class ProductInterceptor implements HandlerInterceptor {


@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("Request URL: " + request.getRequestURL());
log.info("Request Method: " + request.getMethod());
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// Can log response details here
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception {
// Can log completion details here
log.info("Request Process completed");

}
}

Registering the Interceptor

package com.javacodeex.config;

import com.javacodeex.interceprots.LoggingInterceptor;
import com.javacodeex.interceprots.ProductInterceptor;
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 LoggingInterceptor loggingInterceptor;

@Autowired
private ProductInterceptor productInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loggingInterceptor)
.addPathPatterns("/api/**") // Define the URL patterns to be intercepted
.excludePathPatterns("/api/auth/**"); // Define the URL patterns to be excluded from interception

registry.addInterceptor(productInterceptor)
.addPathPatterns("/product/**") // Define the URL patterns to be intercepted
.excludePathPatterns("/api/auth/**");
}
}
package com.javacodeex.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
@Slf4j
public class CustomerController {

@GetMapping
public String getMessage(){
log.info("getMessage()");
return "welcomoe to the interceptors session";
}
}
package com.javacodeex.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {

@GetMapping
public String getProduct(){

log.info("getProduct()");
return "product information";
}
}

Spring Boot Interceptor Lifecycle

  • preHandle: Called before the actual handler is executed. This method can be used for pre-processing (e.g., logging, authentication, etc.). If it returns false, the execution chain is halted.
  • postHandle: Called after the handler is executed but before the ModelAndView is rendered. This method can be used for modifying the ModelAndView before it is rendered.
  • afterCompletion: Called after the complete request has finished. This method can be used for cleanup activities.

Filters and interceptors are both mechanisms for processing HTTP requests and responses in a Spring Boot application, but they operate at different levels and serve different purposes. Here are the key differences between them:

Filters

Lifecycle and Placement:

  • Filters are part of the Servlet API and are configured in the web.xml file or through annotations in a Spring Boot application.
  • Filters are applied to all incoming requests and can be used for tasks such as authentication, logging, and input validation.

Execution Point:

  • Filters are executed before and after the entire request processing, including the dispatching to a servlet or controller.

Scope:

  • Filters can be applied to all or specific URL patterns.
  • They work at the lowest level, before the request reaches the servlet or controller.

Configuration:

  • Filters are configured using the @WebFilter annotation or by registering them as beans in a FilterRegistrationBean.

Use Case:

  • Commonly used for cross-cutting concerns like security, logging, and input/output filtering.

Interceptors

Lifecycle and Placement:

  • Interceptors are part of the Spring MVC framework and are configured using Spring’s configuration classes.
  • Interceptors are used to perform operations before and after the execution of controller methods.

Execution Point:

  • Interceptors are executed at three distinct points in the request lifecycle: before the controller method (preHandle), after the controller method but before the view is rendered (postHandle), and after the complete request is finished (afterCompletion).

Scope:

  • Interceptors can be applied to all or specific URL patterns and can be ordered in a chain.
  • They work at the higher level, interacting with the handler (controller) and the view.

Configuration:

  • Interceptors are configured by implementing the HandlerInterceptor interface and registering them in a configuration class that implements WebMvcConfigurer.

Use Case:

  • Commonly used for tasks like logging, security checks, modifying the ModelAndView object, and other operations that need to occur at specific points in the request lifecycle.

Thank you, keep learning!

java codeex

Thank you for reading until the end. Before you go:

  • Please consider clapping and following the writer! 👏
  • Follow us on YouTube

Follow me for more exciting content

[Follow me on Medium](https://medium.com/@saijanand)

--

--

DevOps.dev
DevOps.dev

Published in DevOps.dev

Devops.dev is a community of DevOps enthusiasts sharing insight, stories, and the latest development in the field.