Spring MVC - HandlerInterceptor
Last Updated :
28 Apr, 2025
Spring interceptor is functional, so let's take a step back and examine the handler mapping. The HandlerInterceptor interface is a handy class offered by Spring. We may override only the relevant methods out of the three by extending this. The HandlerInterceptor interface is implemented by the HandlerInterceptor class, or it can be extended by the Spring Interceptor class.
Spring MVC - HandlerInterceptor Methods
The HandlerInterceptor contains three main methods:
- prehandle(): intercepting requests before they reach the handler, allowing for authentication, logging, or early termination (returns true to proceed, false to stop).
- postHandle(): Executes after the handler but before view rendering, enabling modification of model data or response headers.
- afterCompletion(): Always executes, regardless of handler success or failure, for cleanup tasks, logging, or resource management.
1. preHandle() method
Here’s a simple preHandle() implementation:
@Override
public boolean preHandle(HttpServlet request, HttpServlet responce ,Object handler)
throws Exception{
//here implementation
return false;
}
2. postHandle() method
Here’s a simple postHandle()implementation:
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,Object handler,
ModelAndView modelAndView)
throws Exception {
//Your code
}
3. afterCompletion() method
Here’s a simple afterCompletion() implementation:
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) {
//Your Implementation
}
Spring MVC Interceptor Configuration
The SpringMVCConfig class, which implements WebMvcConfigurer, has an addInterceptors() function that has to be overridden for the Spring Boot project. Our own implementation is represented by the SpringMVCConfig class.
Java
@Configuration
public class SpringMVCConfig implements WebMvcConfigurer {
@Autowired
EmployeeSecurityInterceptor employeeSecurityInterceptor;
@Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(employeeSecurityInterceptor);
}
}
Spring interceptor XML configuration
You can add route patterns on which the interceptor will be called with the aid of XML configuration. As an alternative, we may set up the interceptor to be called in response to every web request.
XML
<!-- Configures Interceptors -->
<mvc:interceptors>
<!-- This XML will intercept all URIs -->
<bean class="org.geeksforgeeks.interceptor.DemoInterceptor"></bean>
<!-- This XML will apply interceptor to only configured URIs -->
<!--
<mvc:interceptor>
<mvc:mapping path="/users"></mvc:mapping>
<bean class="org.geeksforgeeks.interceptor.DemoInterceptor"></bean>
<mvc:interceptor>
-->
</mvc:interceptors>
Examples of Spring MVC - HandlerInterceptor Methods
1. preHandle() Method
preHandle() is called by the interceptor before it processes a request, as the name implies. Defaulting to returning true, this function forwards the request to the handler method.
Java
@Override
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
if (!isAuthenticated(request))
{
response.sendRedirect("/login");
return false; // It will reject the request if it is not authenticated
}
return true;
}
2. postHandle() Method
The interceptor calls this procedure before the DispatcherServlet renders the view, but after the handler has completed its execution. It might be applied to provide ModelAndView more features. There would also be a use case for calculating the processing time of the request.
Java
@Override
public void postHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) throws Exception {
response.setHeader("Cache-Control", "max-age=3600"); //Cache responses for an hour
}
3. afterCompletion() Method
Following the completion of the whole request and the generation of the view, afterCompletion() is called. We can use this technique to get request and response data:
Java
@Override
public void afterCompletion(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
long duration = System.currentTimeSecond() - request.getStartTime();
log.info("Request completed in {}s", duration);
}
Conclusion
So, this is how the Spring MVC HandlerInterceptor.The understanding and proper usage of the Spring MVC HandlerInterceptor have been the main topics of this. The HandlerAdapter is used by the DispatcherServlet to call the method itself. Requests are intercepted and processed by interceptors, in brief. Repetitive handler code, including permission checks and logging, is lessened with their support.
Similar Reads
Spring MVC - Servlet Filter vs Handler Interceptor Filter is a Java class that is executed by the Servlet Container for each incoming HTTP request and each HTTP response. Filter is associated with the Servlet API, while HandlerIntercepter is unique to Spring. Only after Filters will Interceptors begin to operate. HandlerInterceptors are appropriate
3 min read
Spring MVC - Model Interface The Spring Web model-view-controller (MVC) is an open-source framework used to build J2EE web applications. It is based on the Model-View-Controller design pattern and implements the basic features of a core spring framework - Dependency Injection. It is designed around a 'DispatcherServlet' that di
7 min read
Spring MVC Interview Questions and Answers Spring MVC is a powerful Java framework for building web applications. It is known for its complete configuration options, seamless integration with other Java frameworks, and robust architecture. Many top companies, including Netflix, Amazon, Google, and Airbnb, rely on Spring MVC to build scalable
15 min read
Spring Boot - Admin Server Spring boot is one of the most popular applications to develop Java enterprise applications. When you have so many components in your application, you need to monitor and manage them. You have multiple spring boot applications running you need an admin for monitoring. Spring boot admin provides you
4 min read
Hibernate - Interceptors Interceptors are used in conjunction with Java EE managed classes to allow developers to invoke interceptor methods on an associated target class, in conjunction with method invocations or lifecycle events. Common uses of interceptors are logging, auditing, and profiling. The Interceptors 1.1 specif
6 min read
Spring - BeanPostProcessor Spring Framework provides BeanPostProcessor Interface. It allows custom modification of new bean instances that are created by the Spring Bean Factory. If we want to implement some custom logic such as checking for marker interfaces or wrapping beans with proxies after the Spring container finishes
5 min read