Interceptors in Spring MVC
Interceptors in Spring MVC allow you to intercept HTTP requests and responses. They are useful for cross-cutting concerns like logging, authentication, and handling custom logic before or after the execution of a controller. This guide covers the key concepts and usage of interceptors in Spring MVC, including creating, registering, and configuring interceptors.
Key Concepts of Interceptors
- HandlerInterceptor: An interface that provides three methods to intercept requests:
preHandle
,postHandle
, andafterCompletion
. - preHandle: Called before the handler method is invoked.
- postHandle: Called after the handler method has been invoked but before the view is rendered.
- afterCompletion: Called after the complete request has finished.
Creating an Interceptor
To create an interceptor, implement the HandlerInterceptor
interface and override its methods:
LoggingInterceptor.java
// LoggingInterceptor.java
package com.example.springmvc.interceptors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class LoggingInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Pre Handle method is Calling");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("Post Handle method is Calling");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception {
System.out.println("Request and Response is completed");
}
}
Registering the Interceptor
To register an interceptor, configure it in your Spring configuration file using WebMvcConfigurerAdapter
or a Java-based configuration class:
WebConfig.java
// WebConfig.java
package com.example.springmvc.config;
import com.example.springmvc.interceptors.LoggingInterceptor;
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());
}
}
Excluding URL Patterns
You can exclude specific URL patterns from being intercepted:
WebConfig.java (with Exclusions)
// WebConfig.java
package com.example.springmvc.config;
import com.example.springmvc.interceptors.LoggingInterceptor;
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()).excludePathPatterns("/exclude/*");
}
}
Using Multiple Interceptors
You can configure multiple interceptors, and they will be executed in the order they are registered:
AnotherInterceptor.java
// AnotherInterceptor.java
package com.example.springmvc.interceptors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class AnotherInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Another Pre Handle method is Calling");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("Another Post Handle method is Calling");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception {
System.out.println("Another Request and Response is completed");
}
}
WebConfig.java (with Multiple Interceptors)
// WebConfig.java
package com.example.springmvc.config;
import com.example.springmvc.interceptors.LoggingInterceptor;
import com.example.springmvc.interceptors.AnotherInterceptor;
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());
registry.addInterceptor(new AnotherInterceptor());
}
}
Key Points
- HandlerInterceptor: An interface that provides methods to intercept requests:
preHandle
,postHandle
, andafterCompletion
. - preHandle: Called before the handler method is invoked.
- postHandle: Called after the handler method has been invoked but before the view is rendered.
- afterCompletion: Called after the complete request has finished.
- Create interceptors by implementing the
HandlerInterceptor
interface. - Register interceptors using the
InterceptorRegistry
in a configuration class. - Exclude specific URL patterns from being intercepted if needed.
- Configure multiple interceptors and manage their execution order.
Conclusion
Interceptors in Spring MVC provide a powerful mechanism to intercept and manipulate HTTP requests and responses. By implementing and configuring interceptors, developers can address cross-cutting concerns such as logging, authentication, and custom logic execution in a modular and reusable manner. Happy coding!