How to log requests and responses into spring boot using Interceptor. In this Spring Logging example, let’s implement a simple spring boot application to demonstrate the use of Interceptor with spring boot.
Before starting with an example, let us first see what is Interceptors.
What is Interceptor?
When you visit a hospital, you don’t directly go to the doctor. You need to pass through the receptionist, security guard and etc, so these are nothing but the interceptors.
In the same way, in spring, when a request is sent to the controller, It needs to pass through interceptors before processing the request. If you know filter in servlet then you can easily understand interceptor which is quite similar to it. check this article for Filter in servlet https://codedec.com/tutorials/filter-in-servlet/ even if you don’t know, not a problem we will learn in this article.
Interceptors are used to perform tasks such as logging, validation, also we can use interceptors to add any external configuration.
There can be 0 or more interceptors in an application.
How to use Interceptor in Spring boot?
In Spring Boot, you need to define the Interceptor class which implements the HandlerInterceptor interface. We need to override the following three methods:
- preHandle(): This method from the name itself we can understand that is used to intercept the request before it is handled by the handler method of the controller class. This method returns a boolean value i.e if it returns true then continue to the handler method else stop here.
@Overrride public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; }
- postHandle(): This method from the name itself we can understand that is used to intercept the request after it is handled by the handler method of the controller class.
@Override public void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception { }
- afterCompletion(): This is the HandlerInterceptor callback method called after the complete request has finished.
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception { }
Logging Example in Spring Boot using Interceptor
In this example, we will illustrate How to use interceptors to log information. Following is the diagrammatic representation of the interceptor.
Step 1: Open IDE STS- Spring Tool Suite
Step 2: Go to File > Spring Starter Project.
Step 3: Now, fill all the fields as shown below and click Next.
Step 4: Now, Add the dependencies of spring web.
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.abc</groupId> <artifactId>spring-boot-interceptor</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-boot-interceptor</name> <description>Practice</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Project Structure
Configure application. properties file
#change the port number server.port=8888
Create Interceptor class
In this interceptor class, override all the 3 methods. This class will be applied to all the requests going to the handler method.
TestInterceptor.java
package com.abc.example.interceptor.config; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; @Component public class TestInterceptor implements HandlerInterceptor{ Logger logger = LoggerFactory.getLogger(TestInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // TODO Auto-generated method stub logger.info("Executing Before Handler method..."); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { logger.info("Executing After Handler method..."); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TODO Auto-generated method stub logger.info("After completing request..."); } }
Configure Interceptor
package com.abc.example.interceptor.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class InterceptorConfig extends WebMvcConfigurerAdapter { @Autowired TestInterceptor interceptor; @Override public void addInterceptors(InterceptorRegistry registry) { // this interceptor will be applied to all URLs registry.addInterceptor(interceptor); } }
Create a Controller
package com.abc.example.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @RequestMapping("/test") public String home() { System.out.println("Inside handler Method"); return "Hello World !! Start using Interceptors"; } }
- First, annotate this class as @RestController which combines both the annotation @Controller plus @ResposeBody.
- Create a handler method home() that will return the string “Hello World !! Start using Interceptors”.
- Every request for localhost:8888/test URL will be first processed by the interceptors and then will be handled by this handler method.
Run the Application class
package com.abc.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootInterceptorApplication { public static void main(String[] args) { SpringApplication.run(SpringBootInterceptorApplication.class, args); } }
Go to the browser, hit the localhost:8888/test URL, and see the output
Now, go to the console window to view the logging information
In this way, we use an interceptor with a spring boot application.