Spring Boot interceptor example

In this article, we will see the Spring Boot interceptor example. Also, we will see how to configure interceptors using spring boot and what is the use of interceptors. These interceptors will get called before the request will reach to controller/endpoint classes.

 

Define custom interceptors in Spring Boot.

Step 1 – Spring provides HandlerInterceptorAdapter class, we can define custom interceptors extending this class.  HandlerInterceptorAdapter is an abstract class. We need to override the below methods in our interceptor.

boolean preHandle() – This method will get called by container while sending the request to controller classes. Typically used, if we want to send some data with the request or if we want to modify the request data.

void postHandle() – This method will get invoked while sending the response from the server. We can write some logic inside this method if want to modify response data.

afterCompletion() – This method is used for resource clean up task.

Step 2 – We need to define a class WebAppConfigAdapter.java which should implement the WebMvcConfigurer interface and need to override the addInterceptors() method. Using the addInterceptors() method we will add our custom interceptors.

@Override
public void addInterceptors (InterceptorRegistry interceptorRegistry) {
System.out.println("securityInterceptor --" +securityInterceptor);
interceptorRegistry.addInterceptor(securityInterceptor);
}

Note – There is another method afterConcurrentHandlingStarted() can be used instead postHandle() and afterCompletion() when handler is executed concurrently. This method is used for clean up thread-local variables.

Spring Boot interceptor example from scratch.

Create a maven project, Don’t forget to check ‘Create a simple project (skip)’click on next. Fill all details(GroupId – springbootinterceptor, ArtifactId – springbootinterceptor, and name – springbootinterceptor) and click on finish. Keep packaging as the jar.

pom.xml

 

Our directory structure should be as below.

Book.java

 

BooKController.java

 

SpringMainExample.java

 

Now we need to define two classes for interceptor implementation.

InterceptorConfig.java

WebAppConfigAdapter.java

 

We are done now. Let’s run SpringMainExample.java

 

We can see the addInterceptors() method has been called while deployment.

Let’s hit below URI from the postman.

http://localhost:9092/book/getbook

Spring Boot interceptor example

Now preHandle(), postHandle() and afterCompletion() will get called.

org.springframework.boot[email protected]13e16fd: startup date [Sat Feb 23 14:35:06 IST 2019]; root of context hierarchy
this method will get invoked by container while deployment
value of interceptor is [email protected]f
2019-02-23 14:35:09.482 INFO 7252 — [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped “{[/book/getasync],methods=[GET]}” onto public java.util.concurrent.Callable<com.interceptor.entity.Book> com.interceptor.controller.BookController.handleTestRequest()
2019-02-23 14:35:09.483 INFO 7252 — [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped “{[/book/getbook],methods=[GET]}” onto public com.interceptor.entity.Book com.interceptor.controller.BookController.getBook()
2019-02-23 14:35:09.486 INFO 7252 — [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped “{[/error]}” onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>>

org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2019-02-23 14:35:09.486 INFO 7252 — [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped “{[/error],produces=[text/html]}” onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2019-02-23 14:35:09.545 INFO 7252 — [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [
2019-02-23 14:43:42.447 INFO 7252 — [nio-9092-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet ‘dispatcherServlet’
2019-02-23 14:43:42.448 INFO 7252 — [nio-9092-exec-2] o.s.web.servlet.DispatcherServlet : FrameworkServlet ‘dispatcherServlet’: initialization started
2019-02-23 14:43:42.633 INFO 7252 — [nio-9092-exec-2] o.s.web.servlet.DispatcherServlet : FrameworkServlet ‘dispatcherServlet’: initialization completed in 185 ms
preHandle() is invoked
postHandle() is invoked
afterCompletion() is invoked

 

Did you notice! The afterConcurrentHandlingStarted() method has not been called?  This method is used mainly for asynchronous processing. HandlerInterceptorAdapter class further implements AsyncHandlerInterceptor interface, this interface contains afterConcurrentHandlingStarted() method. We have created a new thread using callable in the controller.

 

Let’s clear the console and hit the below URL from the postman.

http://localhost:9091/book/getasync

preHandle() is invoked
afterConcurrentHandlingStarted() is invoked
preHandle() is invoked
postHandle() is invoked
afterCompletion() is invoked

This time the afterConcurrentHandlingStarted() has been invoked.

Real-time use of interceptors.

Modifying RequestAttributes.

Inside preHandle() method We can set the attribute name, value, and scope in request attributes. Further, this request attributes would be set to RequestContextHolder. The benefit would be, we can access these data anywhere in whole application using RequestContextHolder.getRequestAttributes().

Observe the below code snippet.

 

Configure interceptors for logging purposes.

We can also use the interceptors for logging purposes. We can log what request data and response data. Let’s see an example.

 

Call http://localhost:9091/book/getbook and observe the logger info.

INFO 11016 — [nio-9091-exec-4] c.n.interceptors.LoggingInterceptor : /book/getbook
INFO 11016 — [nio-9091-exec-4] c.n.interceptors.LoggingInterceptor : GET

INFO 11016 — [nio-9091-exec-4] c.n.interceptors.LoggingInterceptor : postHanadle() method has been invoked
INFO 11016 — [nio-9091-exec-4] c.n.interceptors.LoggingInterceptor :
INFO 11016 — [nio-9091-exec-4] c.n.interceptors.LoggingInterceptor : afterCompletion() has been invoked
INFO 11016 — [nio-9091-exec-4] c.n.interceptors.LoggingInterceptor : Response status is 200

 

Configuring interceptors for security purposes.

Spring Interceptors can also be used for security-related stuff. Suppose you want to perform authentication and authorization then we can have logic inside preHandle() method. We will have a separate article related to these concepts later.

 

That’s all about the Spring Boot interceptor example.

You may like.

 

Spring interceptors docs.

 

Top