Open In App

Spring MVC – HandlerInterceptor

Last Updated : 05 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads