Using Spring MVC HandlerInterceptor with Spring Boot - Hello World example
We use the interceptor to log the user activity. We will expose an API and then log the status of User interaction.
Video
This tutorial is explained in the below Youtube Video.Lets Begin-

<?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> <groupId>com.javainuse</groupId> <artifactId>springboot-interceptor</artifactId> <version>0.0.1</version> <packaging>jar</packaging> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.0.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
The LoggerInterceptor will override the following methods-
- preHandle() - This method is used to intercept the request before it is handed over to the handler method. If It turns a boolean value, true : continue the handler execution chain; false , stop the execution chain and return it.
- postHandle() - This method is used to intercept the request after the handler execution, Here user can manipulate the ModelAndView object before render it to view page.
- afterCompletion() - This is a HandlerInterceptor callback method called after the complete request has finished.