How to add an Interceptor in a Spring Boot Application

By | August 9, 2020

In this article, we will learn to add an Interceptor in a Spring Boot Application. Let us understand first understand what the is Interceptor.

Whenever you want to send an email to anyone, the first thing is that you must have a personal email id and you should be login or sign in to that, then only it is possible to compose or send an email.

So, in short, you must have these things ready with you before sending an email. That is nothing but called Interceptor. Sign in, log in, or Sign Up Screen is acting as Interceptor.

So in spring boot application, whenever an HTTP request comes to the controller, it should first go through certain things or to perform some other operations before actually accessing the data or executing the controller method.

For example, you can perform some tasks such as verifying the identity of the client, writing the logs files, doing authentication, etc. before processing the request to the controller class.

Under the following two situations in which you can use the Interceptor with Spring Boot Application.

  1. Before executing the controller method based on the HTTP request.
  2. After execution or before sending the response to the client.

Note: Interceptor concept is only applicable when the request is coming to the Controller class.

In order to use the Interceptor, you must have one @Component class and it should implement a HandlerInterceptor interface or extend HandlerInterceptorAdapter class.

When we are dealing or working with Interceptor then there are three methods that we have to use to perform any Interceptor related operations.

  • preHandle(): It used to perform some tasks before processing or sending the HTTP Request to the controller.
  • postHandle(): This method used to perform some operation after executing the HTTP requested API or controller code but it performs all the tasks before giving the response to the client.
  • afterCompletion(): Whatever you write inside this method, it will only be executed after the completion of all the things such as from request to response. This means after giving the response to the client this method code will only get executed.

Let us create a Spring Boot Application that implements the Interceptor.

Step 1: Create a maven project from Spring Initializr.

Step 2: Give the group name, I am giving com.pixeltrice.

Step 3: Fill the artifact field, spring-boot-application-with-interceptor.

Step 4 : Add the Spring web dependency.

Step 5: Click on genrate button. Now project is wrapped in a zip file.

Step 6: Unzipped and import the project in the Eclipse.

Select File -> Import -> Existing Maven Projects -> Browse -> Select the folder spring-boot-application-with-interceptor-> Finish.

Step 7: Create a component class named ProductInterceptor.java that will implement the HandlerInterceptor interface.

All mentioned three methods such as preHandle(), postHandle() and afterCompletion() are declared inside the HandlerInterceptor class. So we need to Override these methods as shown in the below code.

package com.pixeltrice.springbootapplicationwithinterceptor;

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 ProductInterceptor implements HandlerInterceptor {

	
	 @Override
	   public boolean preHandle
	      (HttpServletRequest request, HttpServletResponse response, Object handler) 
	      throws Exception {
	      
	      System.out.println("Inside the Pre Handle method");
	      return true;
	   }
	   @Override
	   public void postHandle(HttpServletRequest request, HttpServletResponse response, 
	      Object handler, ModelAndView modelAndView) throws Exception {
	      
	      System.out.println("Inside the Post Handle method");
	   }
	   @Override
	   public void afterCompletion
	      (HttpServletRequest request, HttpServletResponse response, Object 
	      handler, Exception exception) throws Exception {
	      
	      System.out.println("After completion of request and response");
	   }
}

Step 8: Registered the above class into Interceptor Registry.

For registration purposes, we need one method named addInterceptors(InterceptorRegistry registry), which is present inside the WebMvcConfigurerAdapter class, so we need to extend this class.

Please follow the below code for registering the class.

package com.pixeltrice.springbootapplicationwithinterceptor;

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.WebMvcConfigurerAdapter;

@Component
public class ProductRegistrationConfig extends WebMvcConfigurerAdapter {
	   
	 @Autowired
	 ProductInterceptor productInterceptor;
	   @Override
	   public void addInterceptors(InterceptorRegistry registry) {
		   
	      registry.addInterceptor(productInterceptor);
	   }
	}


Note: Please don’t forget to tag the above class with @Component Annotation. Otherwise, you will not get expected output.

Step 9: Create a simple controller class that contains the HTTP Endpoint or API.

package com.pixeltrice.springbootapplicationwithinterceptor;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProductController {
	
	@RequestMapping("/products")
	void getProduct(){
		System.out.println("Hey wonderful people I am from controller class");
	}
	

}

Step 10: The SpringBootApplication or main class code.

package com.pixeltrice.springbootapplicationwithinterceptor;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootApplicationWithInterceptorApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootApplicationWithInterceptorApplication.class, args);
	}

}

Note: Now we are good to go and run the application to see the output screen.

Make sure the pom.xml file should look like as shown in below code.

<?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.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.pixeltrice</groupId>
	<artifactId>spring-boot-application-with-interceptor</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-boot-application-with-interceptor</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>11</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>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Final File Structure in the workspace inside Eclipse.

How to add an Interceptor in a Spring Boot Application

Step 11: Run the application. After that go to the browser and hit following URL http://localhost:8080/products

Step 12: Go to console window in the Eclipse as shown below.

How to add an Interceptor in a Spring Boot Application

Have you noticed the ouput.

Inside the Pre Handle method
Hey wonderful people I am from controller class
Inside the Post Handle method
After completion of request and response

You can see above that first the statement written inside the preHandle() method got executed, then controller and similarly others.

Download the Source code

Summary

Thank You So much for reading this article. In this tutorial, we learned how to implement the interceptor in the Spring Boot Application. If you have any doubts or queries please do comment below. I will love to answer and help you as soon as possible.

You can also check out my other Spring Boot articles.

Leave a Reply

Your email address will not be published. Required fields are marked *