Spring Boot Interceptor

Farzin Pashaee
4 min readMay 6, 2022

Spring Boot Interceptors are useful tools for intercepting the HTTP request process. The concept is similar to AOP pointcuts and you can have them easily plugged and unplugged from the HTTP request process flow.

Basically, Interceptor is similar to a Servlet Filter, but in contrast to the latter, It is located after DispatcherServlet and as a result, related HandlerInterceptor class configured inside the application context. Filters are known to be more powerful, they are allowed to exchange the request and response objects that are handed down the chain whereas, Interceptors are just allowed to add some customer custom pre-processing, option of prohibiting the execution, and also custom post-processing. You can read about Spring Boot Filter in another post here.

HandlerInterceptor interface

HandlerInterceptor interface from org.springframework.web.servlet package is the interface that needed to be implemented in order to have an interceptor inside your Spring Boot application. This interface has 3 methods that will control the logic needed to be executed at different stages of processing the HTTP requests.

preHandle

This method will be called before sending the request to the controller. Returning false in this method will stop the process from passing the request to the controller

boolean preHandle(
javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response,
java.lang.Object handler)
throws java.lang.Exception

postHandle

This method will be used to perform operations before sending the response to the client.

void postHandle(
javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response,
java.lang.Object handler,
org.springframework.web.servlet.ModelAndView modelAndView)
throws java.lang.Exception

afterCompletion

This method will be used for operations after the whole cycle was completed and the view is generated

--

--

Farzin Pashaee

Software Engineer at Maybank, AI and ML enthusiastic