How to use SpringMVC HandlerInterceptor with Spring Boot

Spring MVC HandlerInterceptor provides a mechanism to intercept requests: pre-processing & post-processing. In the Spring MVC HandlerInterceptor tutorial, JavaSampleApproach will guide you how to use HandlerInterceptor by a Logging sample.


I. Technologies

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.6.RELEASE

II. Overview
1. Project Structure

springmvc HandlerInterceptor project structure

2. Step to do

– Create Spring Boot project
– Create HandlerInterceptor
– Register HandlerInterceptor
– Create Web Controller
– Run & Enjoy result

III. Practice
1. Create Spring Boot project

– Open Spring Tool Suite, on main menu, choose File->New->Spring Starter Project, add project info. Press Next, then Finish, a Spring Boot project will be created successfully.

Open pom.xml file, add Web dependency:


	org.springframework.boot
	spring-boot-starter-web

2. Create HandlerInterceptor

Create LogInterceptor class that implements the interface: HandlerInterceptor
HandlerInterceptor: to customize handler execution chains. Applications can register any number of existing or custom interceptors for certain groups of handlers, to add common preprocessing behavior without needing to modify each handler implementation.

preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception: Intercept the execution of a handler. Called after HandlerMapping determined an appropriate handler object, but before HandlerAdapter invokes the handler.

postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model) throws Exception: Intercept the execution of a handler. Called after HandlerAdapter actually invoked the handler, but before the DispatcherServlet renders the view. Can expose additional model objects to the view via the given ModelAndView.

afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception arg3) throws Exception: Callback after completion of request processing, that is, after rendering the view. Will be called on any outcome of handler execution, thus allows for proper resource cleanup.

package com.javasampleapproach.mvcinterceptor.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 LogInterceptor implements HandlerInterceptor {

	Logger log = org.slf4j.LoggerFactory.getLogger(this.getClass());

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception arg3)
			throws Exception {
		log.info("Request Completed!");
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model)
			throws Exception {
		log.info("Method executed");
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		log.info("Before process request");
		return true;
	}

}
3. Register HandlerInterceptor

Create a configuration class AppConfig that inherits from WebMvcConfigurerAdapter.

WebMvcConfigurerAdapter is an implementation of WebMvcConfigurer with empty methods allowing sub-classes to override only the methods they’re interested in.

WebMvcConfigurer is to define callback methods to customize the Java-based configuration for Spring MVC enabled via @EnableWebMvc.

package com.javasampleapproach.mvcinterceptor.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 AppConfig extends WebMvcConfigurerAdapter {
	
	@Autowired
	LogInterceptor logInterceptor;
	
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(logInterceptor);
	}
}
4. Create Web Controller

Create a simple Spring MVC web controller with only one @RequestMapping(“/hello”)

package com.javasampleapproach.mvcinterceptor.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 SimpleWebController {
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	
	@RequestMapping("/hello")
	public String hello(){
		log.info("Welcome to access RequestMapping: /hello!");
		return "Hello World!";
	}
}
5. Run & Enjoy result

Build & Run the project with Spring Boot App mode.
Make a request: http://localhost:8080/hello
Logs:

[nio-8080-exec-2] c.j.m.config.LogInterceptor              : Before process request
[nio-8080-exec-2] c.j.m.controller.SimpleWebController     : Welcome to access RequestMapping: /hello!
[nio-8080-exec-2] c.j.m.config.LogInterceptor              : Method executed
[nio-8080-exec-2] c.j.m.config.LogInterceptor              : Request Completed!
IV. Sourcecode

SpringMVCHandlerInterceptor

3 thoughts on “How to use SpringMVC HandlerInterceptor with Spring Boot”

    1. Hi Sofiane,

      I had done the double check for you!
      Everything works fine! You can download attached sourcecode for testing.

      New Logs from my test:

      2017-07-24 15:13:39.212  INFO 19596 --- [nio-8080-exec-1] c.j.m.config.LogInterceptor              : Before process request
      2017-07-24 15:13:39.219  INFO 19596 --- [nio-8080-exec-1] c.j.m.controller.SimpleWebController     : Welcome to access RequestMapping: /hello!
      2017-07-24 15:13:39.230  INFO 19596 --- [nio-8080-exec-1] c.j.m.config.LogInterceptor              : Method executed
      2017-07-24 15:13:39.230  INFO 19596 --- [nio-8080-exec-1] c.j.m.config.LogInterceptor              : Request Completed!
      

      -> Should double check you environment:

      – Java 1.8
      – Maven 3.3.9
      – Spring Tool Suite – Version 3.8.1.RELEASE
      – Spring Boot: 1.4.3.RELEASE

      –> Spring Boot: 1.5.4.RELEASE(latest version up to now) is fine.

      Regards,
      JSA

    2. Tha example here is not working because of missing @EnableWebMvc annotation for AppConfig class.
      I just added that annotation and now it’s working fine.

Leave a Reply

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