Configure Interceptor With a Spring Boot
Posted By : Amarjeet Yadav | 21-Apr-2020
In spring Boot when a request is sent to the spring controller, it will have to pass through Interceptors (0 or more) before being processed by Controller.
When you come to a company and want to meet the company's manager. You need to go through interceptors which may be a gatekeeper, a receptionist,...
Spring interceptor could be a construct that's rather like Servlet Filter.
Spring interceptor is simply applied to requests that are sending to a Controller.
You can use an associate interceptor to feature the request header before sending the request to the controller and add the response header before sending the response to the consumer.
You can use an interceptor to try to some tasks like writing log, adding or change configurations before a request is processed by Controller.
To work with the interceptor, you would like to form a @Component category that supports it and it ought to implement the HandlerInterceptor interface.
You need to implement three abstract methods:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
public void postHandle( request, response, handler, modelAndView)
public void afterCompletion( request, response, handler,exception)
You will have to register Interceptor with InterceptorRegistry by using WebMvcConfigurerAdapter as shown below −
After going through this blog, you can use interceptors in an effective way. Just like adding request header(s) before sending the request to the controller or adding the response header(s) before sending the response to the client.