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);
}


Spring MVC – HandlerInterceptor

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.

Similar Reads

Spring MVC – HandlerInterceptor Methods

The HandlerInterceptor contains three main methods:...

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....

Examples of Spring MVC – HandlerInterceptor Methods

...

Conclusion

...