EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Spring Tutorial Spring boot interceptor
Secondary Sidebar
Spring Tutorial
  • Spring Boot
    • What is Spring Boot
    • Spring Boot flyway
    • Spring Boot framework
    • Spring Boot Logback
    • Spring Boot actuator endpoints
    • Spring Boot gRPC
    • Spring Boot jdbctemplate example
    • Spring Boot ehcache
    • Spring Boot Architecture
    • Spring Boot Port
    • Introduction of spring boot
    • Spring Boot ide
    • Spring Boot Netty
    • Spring Boot ORM
    • Spring Boot Versions
    • Spring Boot JUnit
    • Spring Boot Keycloak
    • Spring Boot gradle
    • Spring Boot Lombok
    • Spring Boot autowired
    • Spring Boot bean
    • Spring Boot hibernate
    • Spring Boot integration test
    • Spring Boot jdbc
    • Spring Boot MongoDB
    • Spring Boot postgresql
    • Spring Boot rest
    • Spring Boot swagger
    • Spring Boot thymeleaf
    • Spring Boot Unit Test
    • Spring Boot Webflux
    • Spring Boot webclient
    • Spring Boot kubernetes
    • Spring Boot Properties
    • Spring Boot Validation
    • Spring Boot Feature
    • Spring Boot Application
    • Spring Boot email
    • Spring Boot MVC
    • Spring Boot Exception Handling
    • Spring Boot Starter Parent
    • Spring Boot Docker
    • Spring Boot Logging
    • Spring Boot Query
    • Spring Boot Multiple Data Sources
    • Spring Boot Basic Authentication
    • Spring Boot Test
    • Spring Boot jwt
    • Spring Boot Liquibase
    • Spring Boot Prometheus
    • Spring Boot debug
    • Spring Boot GraalVM
    • Spring Boot Batch
    • Spring Boot controller
    • Spring Boot CLI
    • Spring Boot file upload
    • Spring Boot interceptor
    • Spring Boot Service
    • Spring Boot Configuration
    • Spring Boot Datasource Configuration
    • Spring Boot Annotations
    • Spring Boot Starter We
    • Spring Boot Actuator
    • Spring Boot DevTools
    • Spring Boot Repository
    • Spring Boot Dependencies
    • Spring Boot Path Variable
    • Spring Boot Microservices
    • Spring Boot Run Command
    • Spring Boot application.properties
    • Spring Boot Transaction Management
    • Spring Boot Banner
    • Spring Boot JPA
    • Spring Boot Change Port
    • Spring Boot RestTemplate
    • Spring Boot cors
    • Spring Boot HTTPS
    • Spring Boot OAuth2
    • Spring Boot Profiles
    • Spring Boot Interview Questions
    • Spring Boot filter
    • Spring boot logging level
    • Spring Boot Cache
    • Spring Boot Advantages
    • Spring Boot Scheduler
    • Spring Boot Initializr
    • Spring Boot Maven
    • Spring Boot Admin
    • Spring Boot Tomcat
    • Spring Boot WebSocket
    • Spring Boot Executable Jar
    • Spring Boot CommandLineRunner
    • Spring Boot DataSource
    • Spring Batch Scheduler
    • Spring Batch Example
    • Spring Batch Tasklet
    • Spring Batch Admin
    • Spring Batch
    • Spring Boot Qualifier
    • Spring Boot War
    • Spring Boot Test Configuration
  • Spring
    • What is Spring Framework?
    • Spring Architecture
    • What is Spring Integration?
    • IoC Containers
    • What is AOP?
    • Spring Modules
    • Spring Batch Processing
    • Spring Batch Partitioner
    • Spring Batch Job
    • Spring AOP
    • Spring Expression Language
    • Dependency Injection in Spring
    • Spring Batch Architecture
    • Spring framework Interview Questions
  • Spring Cloud Basics
    • What is Spring Cloud
    • Spring Cloud Contract
    • Spring Cloud Components
    • Spring Cloud Version
    • Spring Cloud Data Flow
    • Spring cloud stream
    • Spring Cloud Dependencies
    • Spring cloud microservices
    • spring cloud gateway
    • Spring Cloud Config
    • Spring Cloud Kubernetes
    • Spring Cloud Sleuth

Related Courses

Spring Boot Certification Course

Spring Framework Course Training

All in One Data Science Course

Spring boot interceptor

Spring boot interceptor

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:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

@Component

Pre handling method in interceptor:

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,754 ratings)

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,

  1. Implementing a direct interface (Interface is called HandleInterceptor)
  2. 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:

Spring boot interceptor output 1

Spring boot interceptor output 2

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 –

  1. Spring Boot Actuator
  2. Spring Boot Annotations
  3. Spring Boot DevTools
  4. Spring Boot Architecture
Popular Course in this category
Spring Boot Training Program (2 Courses, 3 Project)
  2 Online Courses |  3 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Spring Framework Training (4 Courses, 6 Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more