Explain Spring MVC Interceptor

Explain Spring MVC Interceptor

An interceptor in Spring MVC is a component that can intercept requests and responses to perform certain tasks before or after the execution of a controller. Interceptors are used to implement cross-cutting concerns such as logging, authentication, authorization, and modifying the request or response.

Usage

Interceptors are useful for tasks that need to be applied globally or to multiple controllers, such as logging request details, enforcing security, or modifying the request/response data.

Scope

Implemented by creating a class that implements the `HandlerInterceptor` interface or extends the `HandlerInterceptorAdapter` class. This class can then be configured to intercept Spring MVC Interceptor requests in the Spring configuration.

Spring MVC Interceptor

1. Creating an Interceptor
LoggingInterceptor.java
```java
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoggingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // Log request details before handling
        System.out.println("Incoming request data: " + request.getMethod() + " " + request.getRequestURI());
        return true; // Continue with the next interceptor or the handler
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // Optionally log or modify the response after handling
        System.out.println("Response status: " + response.getStatus());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // Clean up resources or log completion details
        System.out.println("Request processing completed");
    }
}
```

In this example:

  • `preHandle`: Logs the request method and URI before the request is processed by the controller.
  • `postHandle`: Logs the response status after the controller has processed the request but before the view is rendered.
  • `afterCompletion`: Logs a message after the request has been fully processed.

Configuring the Interceptor
2. Configuring the Interceptor

WebConfig.java
```java
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());
    }
}
```

In this example:

  • WebConfig implements WebMvcConfigurer and overrides the addInterceptors method to register the LoggingInterceptor.

Example Controller
3. Example Controller

UserController.java
```java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping("/info")
    public String getUserInfo() {
        return "User Info";
    }
}
```

In this example:

  • UserController is a simple controller with a single endpoint /user/info. The interceptor will log request and response details for this endpoint.

Summary of Spring MVC Interceptor

  • Interceptor: A component in Spring MVC used to perform actions before and after request handling, such as logging or modifying requests/responses.
  • preHandle: Executes before the controller method.
  • postHandle: Executes after the controller method but before the view is rendered.
  • afterCompletion: Executes after the complete request has been processed.

Homepage

Readmore