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

...