Spring Boot - Interceptor - Example

Hello everyone, today we will develop a simple Spring Boot application with Spring MVC HandlerInterceptor.
Interceptors working with the HandlerMapping on the framework must implement the HandlerInterceptor interface. HandlerInterceptor is rudimentarily homogeneous to a Servlet Filter, but in contrast to the latter it just allows custom pre-processing with the option of prescribing the execution of the handler itself, and custom post-processing. This interface contains three main methods: 

 Let's begin,

Project Directory:



Maven[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.1.1.RELEASE</version>
<relativePath />
</parent>
<groupId>com.example</groupId>
<artifactId>springboot_Interceptor-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot_Interceptor-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</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>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>


Define the class implementing the spring HandlerInterceptor interface as follows-

package com.knf.dev.interceptor;

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 ServiceInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler)
throws Exception {

System.out.println("Pre Handle method is Calling,
request url" + " " + request.getRequestURI());
return true;
}

@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {

System.out.println("Post Handle method is Calling,
Response status" + " " + response.getStatus());
}

@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler,
Exception exception) throws Exception {

System.out.println("Request and Response is completed");
}
}

prehandle() – called before the genuine handler is executed, but the view is not engendered yet 
postHandle() – called after the handler is executed 
afterCompletion() – called after the consummate request has culminated and the view was 
engendered


Configuration of interceptors:

package com.knf.dev.interceptor;

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 ServiceInterceptorAppConfig implements WebMvcConfigurer {
@Autowired
ServiceInterceptor serviceInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
// Custom interceptor, add intercept path and exclude intercept path
registry.addInterceptor(serviceInterceptor).addPathPatterns("/**");
}
}


HomeController.class(Controller):

package com.knf.dev.controller;

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

@RestController
public class HomeController {

@GetMapping("/hello")
public String getHello() {
return "you are done";
}
}


Finally, create the SpringBoot class annotated with @SpringBootApplication.

package com.knf.dev;

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

@SpringBootApplication
public class SpringbootInterceptorDemoApplication {

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

After running the application- go to http://localhost:8080/hello

In the console, we can see the request gets intercepted as follows-
Pre Handle method is Calling, request url /hello
Post Handle method is Calling, Response status 200
Request and Response is completed

git clone:  

Popular posts from this blog

Spring boot video streaming example-HTML5

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

DataTable-Pagination example with Spring boot, jQuery and ajax

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Node JS mini projects with source code - free download

Spring boot web project free download:User Registration System

Java - Blowfish Encryption and decryption Example