Interceptor in Spring MVC Framework

On the Eclipse, create a Spring MVC project

Enter Project Information:

  • Name: LearnSpringMVCWithRealApps
  • Group: com.demo
  • Artifact: LearnSpringMVCWithRealApps
  • Description: Learn Spring MVC with Real Apps
  • Package: com.demo

Select the technologies and libraries to be used:

  • Web

Click Next button to show Site Information for project

Click Finish button to finish create Spring MVC project




<?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.demo</groupId>
	<artifactId>LearnSpringMVCWithRealApps</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>LearnSpringMVCWithRealApps</name>
	<description>Learn Spring MVC with Real Apps</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>

		<!-- Spring MVC  -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!-- Tomcat for JSP rendering -->
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
			<scope>provided</scope>
		</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>




spring.mvc.view.prefix = /WEB-INF/views/
spring.mvc.view.suffix = .jsp
spring.mvc.static-path-pattern=/resources/**

server.port=9596

Create new package named com.demo.controllers. In this package, create controllers as below:

Create new java class, named Demo1Controller.java

package com.demo.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("demo1")
public class Demo1Controller {

	@RequestMapping(method = RequestMethod.GET)
	public String index() {
		return "demo1/index";
	}

}

Create new java class, named Demo2Controller.java

package com.demo.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("demo2")
public class Demo2Controller {

	@RequestMapping(method = RequestMethod.GET)
	public String index() {
		return "demo2/index";
	}

	@RequestMapping(value = "index2", method = RequestMethod.GET)
	public String index2() {
		return "demo2/index";
	}

	@RequestMapping(value = "index3", method = RequestMethod.GET)
	public String index3() {
		return "demo2/index";
	}

}




Create new folders with path webapp\WEB-INF\views in src\main. In views folder, create views as below:

Create new folder named demo1. Create new jsp file named index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Demo 1</title>
</head>
<body>

	<h3>Demo 1</h3>

</body>
</html>

Create new folder named demo2. Create new jsp file named index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Demo 2</title>
</head>
<body>

	<h3>Demo 2</h3>

</body>
</html>




Create new package named com.demo.interceptors. In this package, create new interceptors as below:

Create new java class, named Log1Interceptor.java

package com.demo.interceptors;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class Log1Interceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		System.out.println("Log 1 - preHandle");
		System.out.println("url: " + request.getRequestURL());
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
		System.out.println("date: " + simpleDateFormat.format(new Date()));
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		System.out.println("Log 1 - postHandle");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		System.out.println("Log 1 - afterCompletion");
	}

}

Create new java class, named Log2Interceptor.java

package com.demo.interceptors;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class Log2Interceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		System.out.println("Log 2 - preHandle");
		System.out.println("url: " + request.getRequestURL());
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
		System.out.println("date: " + simpleDateFormat.format(new Date()));
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		System.out.println("Log 2 - postHandle");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		System.out.println("Log 2 - afterCompletion");
	}

}




Create new package named com.demo.configurations, In this package, create new java class named InterceptorConfiguration.java as below:

package com.demo.configurations;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.demo.interceptors.Log1Interceptor;
import com.demo.interceptors.Log2Interceptor;

@Configuration
public class InterceptorConfiguration implements WebMvcConfigurer {

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new Log1Interceptor());
		registry.addInterceptor(new Log2Interceptor())
				.addPathPatterns("/demo2/*")
				.excludePathPatterns("/demo2/index3");
	}

}




Select LearnSpringMVCWithRealAppsApplication.java file in com.demo package, right click and select Run As/Spring Boot App menu

Access index method in demo1 controller with following url: http://localhost:9596/demo1

Output in Console

Log 1 - preHandle
url: http://localhost:9596/demo1
date: 11/13/2019 15:42:44
Log 1 - postHandle
Log 1 - afterCompletion

Access index method in demo2 controller with following url: http://localhost:9596/demo2

Output in Console

Log 1 - preHandle
url: http://localhost:9596/demo2
date: 11/13/2019 15:44:38
Log 1 - postHandle
Log 1 - afterCompletion

Access index2 method in demo2 controller with following url: http://localhost:9596/demo2/index2

Output in Console

Log 1 - preHandle
url: http://localhost:9596/demo2/index2
date: 11/13/2019 15:45:33
Log 2 - preHandle
url: http://localhost:9596/demo2/index2
date: 11/13/2019 15:45:33
Log 2 - postHandle
Log 1 - postHandle
Log 2 - afterCompletion
Log 1 - afterCompletion

Access index3 method in demo2 controller with following url: http://localhost:9596/demo2/index3

Output in Console

Log 1 - preHandle
url: http://localhost:9596/demo2/index3
date: 11/13/2019 15:46:09
Log 1 - postHandle
Log 1 - afterCompletion