Interceptors in Spring Boot are typically used to intercept and manipulate HTTP requests before they reach the controller or responses before they are sent to the client.
Steps to Implement an Interceptor:
Create an Interceptor Class:
Implement the HandlerInterceptor interface or extend the HandlerInterceptorAdapter class.Override methods like preHandle, postHandle, and afterCompletion based on your needs.
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// Code to execute before the controller method is invoked
System.out.println("Pre Handle method is called");
return true; // If false, the request is not further processed
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// Code to execute after the controller method is invoked, but before the view is rendered
System.out.println("Post Handle method is called");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// Code to execute after the complete request has finished
System.out.println("After Completion method is called");
}
}
Register the Interceptor:
Implement the WebMvcConfigurer interface in a configuration class and override the addInterceptors method to register your interceptor.
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 MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/api/**"); // Specify paths to apply the interceptor
}
}
Interceptors are specific to Spring MVC and operate at the controller level. Interceptors are typically used for concerns like logging, authentication, and modifying model attributes.
Top comments (3)
wow!
good one
Nice article