Member-only story
What is Spring Boot Interceptor and How to Use it?
Interceptor is a specific implementation of Aspect-Oriented Programming, which allows developers to intercept HTTP requests before they reach the Controller and after the Controller has processed them.
There are many use cases for Interceptors.
Consider a case when we must check if a user can use a particular resource. In such cases, the Interceptor can intercept the incoming request. We can then extract the JWT token from the header, validate the token, and, if it is valid, add the corresponding username to the request attribute. We can send a 401 response directly without hitting the Controller if this user is invalid.
My articles are free for everyone. Non-members can read this full article for free HERE.
It can also be used for other purposes like logging, updating configs, etc.
Interceptors sit between the Client and the Controller, allowing us to perform operations before and after the Controller’s execution.
How to Create an Interceptor in Springboot?
First, we need to implement HandlerInterceptor. There are three key methods that we need to override.
- preHandle(): This is executed before the Controller method processes the request. You can have…