Spring Boot: Interceptor

Deepak jha
3 min readJan 24, 2021

--

In this blog, I will explain spring interceptor and how we can use that.

Interceptor is very similar to filters in a servlet, that is any request from the client doesn't directly go to the servlet. A Servlet filter is an object that can intercept HTTP requests, and it has to go through various filters and after that, the request can be processed by the servlet, servlet filters are mainly used to perform filtering tasks like logging request parameters to log files, Authentication and authorization, Compressing the response data sent to the client, encryption and decryption, input validation, etc.

Similarly in our spring boot application, we can create an interceptor that will help us to perform operations before sending the request to the controller and before sending the response to the client.

Interceptor is working with the HanderMapping which create a chain of interceptor and we can define which request need some kind of operation, like many endpoints in our application is secure and we need to authorize every client before processing there request in order to check if the client is valid or not.

In order to create an interceptor, we have to implement a HandlerInterceptor interface and have to override the three methods.

  • prehandle(): This method is used when we have to perform any kind of operation before sending a request to the controller, here we can log a request to any file and perform authorization, etc.
  • postHandle(): This method is used after our request is processed and then we have to perform any kind of operation before sending the response to the client.
  • afterCompletion(): This method is used to perform any operation after request and response are complete.

These three methods allow us to do all kinds of pre- and post-processing. We can implement this with the help of the HandlerInterceptor and HandlerInterceptorAdapter class, but the basic difference between them is when implementing HandlerInterceptor we have to override all three methods, but extending HandlerInterceptorAdapter we can override only required methods.

Example: HandlerInterceptor,

prehandle
postHandle
afterCompletion

I hope you understand the need for an interceptor in our application and also how we can create one, and it is very useful.

--

--

No responses yet