Introduction

In this quick tutorial, we'll create interceptor in Spring Boot. 

In Spring, interceptors are used in the following situations:

  • before the request reaches the controller
  • right before the response is sent to the client

Interceptors are useful when you need some sort of request pre-processing or response post-processing, for example - you can add missing field or header to request, or add a header to the response. Another use is request filtering - in case you want to process only requests that contain certain elements or values.

Important interceptor methods you should know about are:

  • preHandle() method − use this method to perform operations before sending the request to the controller. This method returns boolean, and if it returns true, your request will be processed further. 

  • postHandle() method − It returns void, use it for operations that should execute before sending the response to a client.

    afterCompletion() method − this method will execute after the request is processed and the response is sent.

In this example, we'll show you what's needed to create interceptor in Spring Boot - we'll set up three interceptor methods, one per method type mentioned above.

Implementation - create interceptor in Spring Boot

We'll add simple controller, just for example purposes:

package com.example.demo.controller;

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

@RestController
public class DemoController {

	@GetMapping("/api/demo")
	public String getText() {
		System.out.println("Entered controller.");
		return "some text";
	}
}

First, we create an interceptor class and override one of the methods mentioned above. In this example, we'll implement all three interceptor method types and only print one line in them. Notice that our class extended HandlerInterceptorAdapter class and that it's classified as @Component.

package com.example.demo.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component
public class DemoInterceptor extends HandlerInterceptorAdapter {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("Entered preHandle interceptor.");
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) {
		System.out.println("Entered postHandle interceptor.");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception exception) {
		System.out.println("Entered afterCompletion iterceptor");
	}
}

As mentioned, preHandle method should return boolean, so we return true here. Other two interceptor method types return void. This means that after the interceptor is executed, the application will continue request processing. We also need to register this interceptor class (I hope soon there will be some sort of annotation for this):

package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.example.demo.interceptor.DemoInterceptor;

@Configuration
public class DemoConfiguration implements WebMvcConfigurer {

	@Autowired
	DemoInterceptor demoInterceptor;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(demoInterceptor);
	}

}

When we run this application and invoke endpoint we created, the console will show:

Entered preHandle interceptor.
Entered controller.
Entered postHandle interceptor.
Entered afterCompletion iterceptor.

Just to mention, the only dependency you need for adding interceptors in your project is spring-boot-starter-web:

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
</dependencies>

Source code is available on GitHub.

We also created video guide for this tutorial: