Spring5 MVC HandlerInterceptor XMLConfig Example

By | | Updated : 2018-12-05 | Viewed : 427 times

Spring5 MVC HandlerInterceptor XMLConfig Example

We will try and execute the example for HandlerInterceptor example. Please click here to know about the HandlerInterceptor introduction.

We will try and execute the example for HandlerInterceptor example. Please click here to know about the HandlerInterceptor introduction.

Spring5 MVC HandlerInterceptor XML Config Example

    Requirements

  • Spring5 Web MVC

  • Java 1.8+

  • Eclipse 4.8.0

  • Servlet 4.0

  • apache-tomcat-9.0.12

To create maven project in eclipse follow the below given steps.

Create Maven project for Spring5 MVC HandlerInterceptor XMLConfig Example
Click on File tab 
--> New 
--> Click on Maven Project 
--> Please check on Create Simple Project (Skip architype selection) 
--> Click on Next --> Enter the values com.docsconsole.tutorials.springmvc5 as Group Id, Spring5-MVC-HandlerInterceptor-XMLConfig-Example as Artifact Id 
--> Select packaging option as War
--> Click on Finish

Please find the updated pom.xml file given below.

pom.xml
<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.docsconsole.tutorials.springmvc5</groupId>
	<artifactId>Spring5-MVC-HandlerInterceptor-XMLConfig-Example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>Spring5-MVC-HandlerInterceptor-XMLConfig-Example</name>
	<description>Spring5-MVC-HandlerInterceptor-XMLConfig-Example</description>

	<properties>
		<springframework.version>5.1.2.RELEASE</springframework.version>
		<maven.war.plugin.version>3.2.2</maven.war.plugin.version>
		<servlets.version>4.0.0</servlets.version>
		<jsp.version>2.3.1</jsp.version>
		<jstl.version>1.2.2</jstl.version>
		<tld.version>1.1.2</tld.version>
		<log4j.version>1.2.17</log4j.version>
		<maven.compiler.source>9</maven.compiler.source>
		<maven.compiler.target>9</maven.compiler.target>
	</properties>

	<dependencies>

		<!-- Spring core dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${springframework.version}</version>
		</dependency>

		<!-- Spring MVC dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${springframework.version}</version>

		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${springframework.version}</version>
		</dependency>

		<!-- Servlet Dependency -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlets.version}</version>
			<scope>provided</scope>
		</dependency>

		<!-- JSP Dependency -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>${jsp.version}</version>
			<scope>provided</scope>
		</dependency>

		<!-- JSTL Dependency -->
		<dependency>
			<groupId>javax.servlet.jsp.jstl</groupId>
			<artifactId>javax.servlet.jsp.jstl-api</artifactId>
			<version>${jstl.version}</version>
		</dependency>

		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>${tld.version}</version>
		</dependency>

		<!-- Log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
	</dependencies>

	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-war-plugin</artifactId>
					<version>${maven.war.plugin.version}</version>
					<configuration>
						<warSourceDirectory>src/main/webapp</warSourceDirectory>
						<warName>${project.artifactId}</warName>
						<failOnMissingWebXml>false</failOnMissingWebXml>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>

Please create web.xml and spring-dispatcher-servlet.xml as given below under WEB-INF directory.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
  <display-name>Basic Example for Spring5 MVC</display-name>
  <servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
spring-dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

	<context:component-scan base-package="com.docsconsole.tutorials.springmvc5.*" />
	
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>
	
	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/getAdminHome" />
			<bean class="com.docsconsole.tutorials.springmvc5.interceptor.AdminRequestInterceptor" />
		</mvc:interceptor>
		<mvc:interceptor>
			<mvc:mapping path="/getUserHome" />
			<bean class="com.docsconsole.tutorials.springmvc5.interceptor.UserRequestInterceptor" />
		</mvc:interceptor>
	</mvc:interceptors>
	
</beans>

Here we have configured two tags in which will be used for configuring the interceptors. Here we are intercepting two requests. Requests, to be intercepted, are /getAdminHome and /getUserHome. These two requests we configured in .

We configured the in tag . So when we enter request path in the browser client, which contains /getAdminHome or /getUserHome, then request will be intercepted and executed all the methods in customizedIntercepter (AdminRequestInterceptor or UserRequestInterceptor).

In next step, we need to implement two java classes AdminRequestInterceptor and UserRequestInterceptor.

AdminRequestInterceptor.java
package com.docsconsole.tutorials.springmvc5.interceptor;

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

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class AdminRequestInterceptor extends HandlerInterceptorAdapter {
	private static final Logger logger = Logger.getLogger(AdminRequestInterceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.info("Request intercepted @preHandle-AdminRequestInterceptor");
		logger.info("Request URL::" + request.getRequestURL().toString());
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		logger.info("Request intercepted @postHandle-AdminRequestInterceptor");
		logger.info("Request URL::" + request.getRequestURL().toString());
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		logger.info("Request intercepted @afterCompletion-AdminRequestInterceptor");
		logger.info("Request URL::" + request.getRequestURL().toString());
	}
}
UserRequestInterceptor.java
package com.docsconsole.tutorials.springmvc5.interceptor;

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

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class UserRequestInterceptor extends HandlerInterceptorAdapter {
	private static final Logger logger = Logger.getLogger(UserRequestInterceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		logger.info("Request intercepted @preHandle-UserRequestInterceptor");
		logger.info("Request URL::" + request.getRequestURL().toString());
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		logger.info("Request intercepted @postHandle-UserRequestInterceptor");
		logger.info("Request URL::" + request.getRequestURL().toString());
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		logger.info("Request intercepted @afterCompletion-UserRequestInterceptor");
		logger.info("Request URL::" + request.getRequestURL().toString());
	}
}

To handle the request, we need to write the one Controller class. Please write code for HomeController.java as given below.

HomeController.java
package com.docsconsole.tutorials.springmvc5.conntroller;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.docsconsole.tutorials.springmvc5.interceptor.AdminRequestInterceptor;

@Controller
public class HomeController {
	private static final Logger logger = Logger.getLogger(HomeController.class);
	@RequestMapping(value="/getAdminHome", method = RequestMethod.GET)
	public String getAdminHome(ModelMap model) {
		
		logger.info("Request @getAdminHome-HomeController");
		model.addAttribute("msg", "Welcome Admin to AdminHome Page !!");
		logger.info("Sending response @getAdminHome-HomeController");
		return "adminHome";		
		
	}
	
	@RequestMapping(value="/getUserHome", method = RequestMethod.GET)
	public String getUserHome(ModelMap model) {
		
		logger.info("Request @getUserHome-HomeController");
		model.addAttribute("msg", "Welcome User to UserHome Page !!");
		logger.info("Sending response @getUserHome-HomeController");
		return "userHome";		
		
	}
}

As we displaying the results in logs, we need to create log4j.properties under resources folder. Please update all the properties as given below.

log4j.properties
#Root logger options

log4j.rootLogger=DEBUG, console, file


# Console appender

log4j.appender.console=org.apache.log4j.ConsoleAppender

log4j.appender.console.Target=System.out

log4j.appender.console.layout=org.apache.log4j.PatternLayout

log4j.appender.console.layout.ConversionPattern=%-5p %c{1} - %m%n


#log messages to a log file

log4j.appender.file=org.apache.log4j.RollingFileAppender

#outputs to Tomcat home

log4j.appender.file.File=${catalina.home}/logs/spring-handlerInterceptor.log

log4j.appender.file.MaxFileSize=10MB

log4j.appender.file.MaxBackupIndex=20

log4j.appender.file.layout=org.apache.log4j.PatternLayout

log4j.appender.file.layout.ConversionPattern=%d %d{Z} [%t] %-5p (%F:%L) - %m%n

To display results as view we need to create adminHome.jsp and userHome.jsp. Please find below given code snippets for the same.

adminHome.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
   <head>
      <title>Spring5-MVC-HandlerInterceptor-XMLConfig-Example</title>
   </head>
   
   <body>
      <h2 style="color: #528396;padding: 20 0 0 40;">${msg}</h2>
   </body>
</html>
userHome.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
   <head>
      <title>Spring5-MVC-HandlerInterceptor-XMLConfig-Example</title>
   </head>
   
   <body>
      <h2 style="color: #528396;padding: 20 0 0 40;">${msg}</h2>
   </body>
</html>

Please find below given the image for project architecture directory.

Spring5-MVC-HandlerInterceptor-XMLConfig-Example

After deploying the war for please use below given URL then you will get out as given screenshots.

http://localhost:8080/Spring5-MVC-HandlerInterceptor-XMLConfig-Example/getAdminHome http://localhost:8080/Spring5-MVC-HandlerInterceptor-XMLConfig-Example/getUserHome

Spring5-MVC-HandlerInterceptor-XMLConfig-Example
Spring5-MVC-HandlerInterceptor-XMLConfig-Example

You can find the log messages in Tomcat-Home/logs/spring-handlerInterceptor.log as given below.

spring-handlerInterceptor.log
2018-12-06 22:44:55,189 +0530 [http-nio-8080-exec-6] INFO  (AdminRequestInterceptor.java:15) - Request intercepted @preHandle-AdminRequestInterceptor
2018-12-06 22:44:55,193 +0530 [http-nio-8080-exec-6] INFO  (AdminRequestInterceptor.java:16) - Request URL::http://localhost:8080/Spring5-MVC-HandlerInterceptor-XMLConfig-Example/getAdminHome
2018-12-06 22:44:55,199 +0530 [http-nio-8080-exec-6] INFO  (HomeController.java:17) - Request @getAdminHome-HomeController
2018-12-06 22:44:55,200 +0530 [http-nio-8080-exec-6] INFO  (HomeController.java:19) - Sending response @getAdminHome-HomeController
2018-12-06 22:44:55,202 +0530 [http-nio-8080-exec-6] INFO  (AdminRequestInterceptor.java:24) - Request intercepted @postHandle-AdminRequestInterceptor
2018-12-06 22:44:55,205 +0530 [http-nio-8080-exec-6] INFO  (AdminRequestInterceptor.java:25) - Request URL::http://localhost:8080/Spring5-MVC-HandlerInterceptor-XMLConfig-Example/getAdminHome
2018-12-06 22:44:55,442 +0530 [http-nio-8080-exec-6] INFO  (AdminRequestInterceptor.java:31) - Request intercepted @afterCompletion-AdminRequestInterceptor
2018-12-06 22:44:55,444 +0530 [http-nio-8080-exec-6] INFO  (AdminRequestInterceptor.java:32) - Request URL::http://localhost:8080/Spring5-MVC-HandlerInterceptor-XMLConfig-Example/getAdminHome

2018-12-06 22:47:46,310 +0530 [http-nio-8080-exec-9] INFO  (UserRequestInterceptor.java:16) - Request intercepted @preHandle-UserRequestInterceptor
2018-12-06 22:47:46,311 +0530 [http-nio-8080-exec-9] INFO  (UserRequestInterceptor.java:17) - Request URL::http://localhost:8080/Spring5-MVC-HandlerInterceptor-XMLConfig-Example/getUserHome
2018-12-06 22:47:46,317 +0530 [http-nio-8080-exec-9] INFO  (HomeController.java:27) - Request @getUserHome-HomeController
2018-12-06 22:47:46,319 +0530 [http-nio-8080-exec-9] INFO  (HomeController.java:29) - Sending response @getUserHome-HomeController
2018-12-06 22:47:46,321 +0530 [http-nio-8080-exec-9] INFO  (UserRequestInterceptor.java:25) - Request intercepted @postHandle-UserRequestInterceptor
2018-12-06 22:47:46,323 +0530 [http-nio-8080-exec-9] INFO  (UserRequestInterceptor.java:26) - Request URL::http://localhost:8080/Spring5-MVC-HandlerInterceptor-XMLConfig-Example/getUserHome
2018-12-06 22:47:46,332 +0530 [http-nio-8080-exec-9] INFO  (UserRequestInterceptor.java:32) - Request intercepted @afterCompletion-UserRequestInterceptor
2018-12-06 22:47:46,333 +0530 [http-nio-8080-exec-9] INFO  (UserRequestInterceptor.java:33) - Request URL::http://localhost:8080/Spring5-MVC-HandlerInterceptor-XMLConfig-Example/getUserHome

    Dispatcher Servlet is used to HandlerAdapter to invoke handler methods. Here execution order will be decided by HandlerExecutionChain.

  • 1. preHandle()method in AdminRequestInterceptor class is invoked.

  • 2. getAdminHome()method in HomeController class is invoked

  • 3. postHandle() method in AdminRequestInterceptor class is invoked.

  • 4. afterCompletion() method in AdminRequestInterceptor class is invoked.

Leave A Reply