Spring Boot Interceptor example
The example below shows how to create an Interceptor in Spring Boot using Spring HandlerInterceptor
In Spring Boot web application, you can register interceptors for the handlers to implement common checking or logic. For example, a handler interceptor can check the time taken by request, check authorization, perform auditing etc.
An Interceptor is similar to a Servlet Filter, but an Interceptor allows custom pre-processing and you can also stop the execution of the handler and custom post-processing.
Implementing Interceptor
To create an interceptor in Spring Boot, you need to implement the HandlerInterceptor interface. You need to implement following three methods defined in HandlerInterceptor interface:
- preHandle() method - this is called after handler object is chosen, but before HandlerAdapter invokes the handler.
- postHandle() method - this is called after HandlerAdapter invokes the handler, but before the DispatcherServlet renders the view.
- afterCompletion() method - this is called after request is processed and view is rendered.
In the example below we will create a Logging interceptor and see how it gets invoked in a Spring Boot application
Step 1) Create 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 http://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.1.6.RELEASE</version> <relativePath/> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Spring Boot Interceptor</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <!-- To create an executable jar --> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Step 2) Create SpringBootInterceptorApplication class
package com.example.demo; 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); } }
Step 3) Create SpringBootInterceptorController class
package com.example.demo; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SpringBootInterceptorController { @GetMapping("/") public String hello() { System.out.println("Returning respone"); return "Hello World"; } }
Step 4) Create LoggingInterceptor class which will act as an interceptor in this Spring Boot application.
package com.example.demo; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; @Component public class LoggingInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("Pre Handle method is Calling"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("Post Handle method is Calling"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception { System.out.println("Request and Response is completed"); } }
Step 5) Create InterceptorConfig class
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.config.annotation .InterceptorRegistry; import org.springframework.web.servlet.config.annotation .WebMvcConfigurer; @Component public class InterceptorConfig implements WebMvcConfigurer { @Autowired LoggingInterceptor loggingInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loggingInterceptor).addPathPatterns("/**"); } }
Step 7) Run SpringBootInterceptorApplication
Open any browser and launch http://localhost:8080. You will see 'Hello World' message displayed in the broswer.Observe the logs below which shows the log messages from the LoggingInterceptor class
Pre Handle method is Calling Returning respone Post Handle method is Calling Request and Response is completed
References :
Spring HandlerInterceptor