Updated April 1, 2023
Introduction to Spring boot interceptor
Spring boot interceptor is defined as a concept that is invoked at the time of preprocessing and post-processing of a request and allows the only filtered request to the controllers to process it. We can assume it to be analogous to a situation where a visitor wants to meet the CEO of an organization. In the scenario, the visitor needs to pass through a lot of checks and protocols in order to be qualified to meet the CEO, for example, availability of an appointment, passing through security checks, etc. the concept of interceptor is very similar to servlet filter and are applied to requests that are being sent to the controller. For example, adding/updating configurations, writing logs are some tasks that the interceptor performs before the controller processes the request.
Syntax
The spring boot interceptor, as mentioned, is a methodology for putting in checks for the requests before it passes to the controller for its operations. In this section, we will learn about the spring boot interceptor from the syntax perspective so that when we learn about the working of the spring boot interceptor and its features, mapping back to the syntax will enable looking at the complete picture of the topic in the discussion of the article.
Decorator needed for working with interceptor in Spring Boot application:
@Component
Pre handling method in interceptor:
preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
Post handling method in interceptor:
postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
After completion method in interceptor:
afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
Registering the interceptor with InterceptorRegistry by the usage of adapter:
@Override
public void addInterceptors(InterceptorRegistry registry) {
}
How does interceptor work in Spring boot?
Before we start understanding Spring Boot Interceptors’ working, we need to understand the utility of interceptors. Now, though we are talking about interceptors in Spring Boot, one needs to know that the concept of interceptor is not specific to Spring Boot but is considered a standard of J2EE. For example, requests in a web application can be intercepted for various reasons, viz. logging, country-specific request filtering, etc. Hence one needs to make sure that before a request is served, logging the origin of the request and then modifying the header file and append it into desired things is taken care of by interceptors. Now, one might think that why one would take the pain of making an interceptor, where loggers and optimizers can achieve the quantum of the task. The answer to this is when loggers and optimizers are written, each and every controller might tend to creep in anomalies and increase the code overhead. Therefore, the interceptor places the codes by associating them with as many access points as needed and deciphering each request before the request reaches the path controller.
In Spring boot interceptor is implemented in 2 ways, namely,
- Implementing a direct interface (Interface is called HandleInterceptor)
- By extending an instance of HandleInterceptorAdapter.
For the simplicity of the article, we will go through the methodology of extending an instance of HandleInterceptorAdapter. These 3 functions need to be overwritten, namely preHandle, postHandle, afterCompletion. Through these 3 functions, the utility of the interceptor is achieved and hence becomes the important source to understand the working of the interceptor.
The request first encounters the preHandle function before the request is handed over to the controller. The return of the “True” value is very important in order to allow the request to proceed ahead with the further operations on the request. Return of False signifies that no further processing is required as the spring interceptor has handled the request all by itself. The response object is used to send the response to the client without invoking the postHandle and afterCompletion. Till now, the view is not generated yet, and the handler object to handle the request. Now when the controller processes the request, and before it reaches the client, postHandle is invoked. This is done to perform the operation before the request is sent back to the client. This method is generally used for the addition of attributes to the ModelAndView object, which are consumed in the view pages. Not only this but the method is also used to determine the time taken by the handler method in processing the client request. Post this; the View is created. Now once the handler gets executed and the view is rendered, the after completion function is called to complete the cycle.
In this way of working, the interceptor acts as a broker to the request that needs to reach the controller, just like the checks that happen for a visitor when the visitor needs to meet the concerned person.
Example of Spring boot interceptor
Given below are the example of Spring boot interceptor:
Example – Understanding the flow of requests:
Syntax
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>
<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.7</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>
DemointerceptorApplication.java within com.educba.interceptor package
package com.educba.interceptor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemointerceptorApplication {
public static void main(String[] args) {
SpringApplication.run(DemointerceptorApplication.class, args);
}
}
InterceptorConfig.java within com.educba.interceptor.config package
package com.educba.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
LoggerInterceptor logInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(logInterceptor);
}
}
LoggerInterceptor.java within com.educba.interceptor.config package
package com.educba.interceptor.config;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class LoggerInterceptor implements HandlerInterceptor {
Logger logIntercept = org.slf4j.LoggerFactory.getLogger(this.getClass());
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object object, Exception arg3)
throws Exception {
logIntercept.info("State: After completion");
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object object, ModelAndView model)
throws Exception {
logIntercept.info("State: Post request is handled");
}
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object object) throws Exception {
logIntercept.info("State: Before request reaches controller");
return true;
}
}
LoggerController.java within com.educba.interceptor.controller package
package com.educba.interceptor.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoggerController {
Logger logIntercept = LoggerFactory.getLogger(this.getClass());
@RequestMapping("/endpoint")
public String executeLogger() {
logIntercept.info("Executing the Logger method");
return "Demo on Interceptor powered by eduCBA!";
}
}
Output:
Conclusion
In conclusion, in this article, we have learned about the working of spring boot interceptor and the alternative ways on how it can be implemented in Spring Boot to the developers with taking care of logging during the processing of request so that no extra logger is required and everything is consistent. Therefore, we encourage readers to try the example hands-on along with any additional idea to “learn from experience”!
Recommended Articles
This is a guide to Spring boot interceptor. Here we discuss the working of the spring boot interceptor along with the alternative ways. You may also have a look at the following articles to learn more –