Spring Boot Interceptor Example (2024)
In this tutorial, we'll demonstrate how to create a Spring Boot Interceptor with rest api to test.
Q: What is an Interceptor in Spring Boot?
Ans:
When a request is delivered to the Spring Controller, it must travel through one or more Interceptors before being handled by the Controller. The concept of Spring Interceptor is similar to that of Servlet Filter. Only requests sent to a Controller are intercepted by Spring Interceptor. Before the request is processed by Controller, we can utilize Interceptor to do activities such as user authentication, log writing, and adding or modifying configurations.
Create Spring Boot application
Create Spring Boot application from Spring Initializr.
Project Structure
Add Dependencies
Add spring-boot-starter-web
dependency in 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.3.4.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.techgeeknext</groupId>
<artifactId>spring-boot-interceptors-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-interceptors-example</name>
<description>Spring Boot interceptors Example</description>
<properties>
<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>
Take a look at our suggested posts:
Handler Interceptors
The HandlerInterceptor
interface must be implemented or extended from the HandlerInterceptorAdapter
class. All request go through the interceptor coming for Controller.
Three abstract methods must be implemented: preHandle, postHandle, and afterCompletion. Each request is processed by an Interceptor.
package com.techgeeknext.interceptor;
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.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
@Component
public class EmployeeLoginInterceptor extends HandlerInterceptorAdapter {
Logger logger = LoggerFactory.getLogger(EmployeeLoginInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
logger.info("====== Employee Login PreHandle Interceptor to do authentication logic ======");
//we can returns true or false
// depending on our logic to allow user to access rest controller api
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) {
logger.info("====== Employee Login PostHandle Interceptor ======");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception exception) {
logger.info("====== Employee Login AfterCompletion Interceptor ======");
}
}
Configure Interceptor
package com.techgeeknext.config;
import com.techgeeknext.interceptor.EmployeeLoginInterceptor;
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.WebMvcConfigurer;
@Configuration
public class EmployeeConfiguration implements WebMvcConfigurer {
@Autowired
EmployeeLoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor);
}
}
Rest Controller
Create EmployeeController
to test Interceptor. All request to the /login
endpoint will go through first Interceptor methods.
package com.techgeeknext.controller;
import com.techgeeknext.interceptor.EmployeeLoginInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmployeeController {
Logger logger = LoggerFactory.getLogger(EmployeeController.class);
@GetMapping("/login")
public String login() {
logger.info("====Employee Login Controller=====");
return "Employee Login";
}
}
Test Spring Boot Interceptor Example
- Start the Spring Boot Application by running
spring-boot:run
or by running main class. - Go to http://localhost:8080/login rest endpoint to test the interceptor feature.
- We can see the output in the console that
PreHandle
method -> Rest Controller ->PostHandle
->AfterCompletion
Interceptor methods will invoked in this sequence.. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.3.4.RELEASE) 11:31:24.863 INFO 20372 --- [main] c.t.SpringInterceptorApplication : Starting SpringInterceptorApplication on PID 20372 (D:\spring-boot-interceptors-example\target\classes started by Milind in D:\spring-boot-interceptors-example) 11:31:24.872 INFO 20372 --- [main] c.t.SpringInterceptorApplication : No active profile set, falling back to default profiles: default 11:31:27.085 INFO 20372 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 11:31:27.103 INFO 20372 --- [main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 11:31:27.103 INFO 20372 --- [main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.38] 11:31:27.229 INFO 20372 --- [main] o.a.c.c.C.[Tomcat].[localhost].[/]: Initializing Spring embedded WebApplicationContext 11:31:27.229 INFO 20372 --- [main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2248 ms 11:31:27.524 INFO 20372 --- [main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 11:31:27.788 INFO 20372 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 11:31:27.801 INFO 20372 --- [main] c.t.SpringInterceptorApplication : Started SpringInterceptorApplication in 3.572 seconds (JVM running for 4.248) 11:31:42.321 INFO 20372 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]: Initializing Spring DispatcherServlet 'dispatcherServlet' 11:31:42.321 INFO 20372 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' 11:31:42.332 INFO 20372 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 10 ms 11:31:42.420 INFO 20372 --- [nio-8080-exec-1] c.t.i.EmployeeLoginInterceptor: ====== Employee Login PreHandle Interceptor to do authentication logic ====== 11:31:42.437 INFO 20372 --- [nio-8080-exec-1] c.t.controller.EmployeeController : ====Employee Login Controller===== 11:31:42.478 INFO 20372 --- [nio-8080-exec-1] c.t.i.EmployeeLoginInterceptor: ====== Employee Login PostHandle Interceptor ====== 11:31:42.479 INFO 20372 --- [nio-8080-exec-1] c.t.i.EmployeeLoginInterceptor: ====== Employee Login AfterCompletion Interceptor ======
Download Source Code
The full source code for this article can be found below.
- Download it here - Spring Boot Interceptor Example