×
DocsConsole

DocsConsole

Spring5 MVC HandlerInterceptor JavaConfig Example

By | | Updated : 2018-12-08 | Viewed : 337 times

Spring5 MVC HandlerInterceptor JavaConfig Example

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

We will try and execute the example for HandlerInterceptor example with JavaCofig. Please click here to know about the HandlerInterceptor XMLConfig 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 JavaConfig 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-JavaConfig-Example as Artifact Id 
--> Select packaging option as War
--> Click on Finish
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-JavaConfig-Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>Spring5-MVC-HandlerInterceptor-JavaConfig-Example</name>
  <description>Spring5-MVC-HandlerInterceptor-JavaConfig-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>

		<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>

We are using java for configuration. Please find below given java file regarding configuration.

WebAppInitializer.java
package com.docsconsole.tutorials.springmvc5.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { WebMvcConfig.class };
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return null;
	}

	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}
}

We can configure the WebAppInitializer.java by extending AbstractAnnotationConfigDispatcherServletInitializer. We can also use WebApplicationInitializer.java. Please click here to find more details. But recommended one is AbstractAnnotationConfigDispatcherServletInitializer implementation which is provided by Spring. Here we configured without hierarchyContext.

We can configure the WebAppInitializer.java by extending AbstractAnnotationConfigDispatcherServletInitializer. We can also use WebApplicationInitializer.java. Please click here to find more details. But recommended one is AbstractAnnotationConfigDispatcherServletInitializer implementation which is provided by Spring. Here we configured without hierarchyContext.

Use @Bean to configure interceptors as given bellow.

Defining of interrupters using @Bean
@Bean
AdminRequestInterceptor gdminRequestInterceptor() {
	return new AdminRequestInterceptor();
}

@Bean
UserRequestInterceptor userRequestInterceptor() {
	return new UserRequestInterceptor();
}

These beans should be registered in InterceptorRegistry as given below.

Registration of Interceptors
@Override
public void addInterceptors(InterceptorRegistry registry) {
	registry.addInterceptor(gdminRequestInterceptor()).addPathPatterns("/getAdminHome");
	registry.addInterceptor(userRequestInterceptor()).addPathPatterns("/getUserHome");
}

When we enter the URL, which contains "/getAdminHome" in the browser then request will intercepted and control will be sending to the configured intercepter i.e., AdminRequestInterceptor. When we enter the URL, which contains "/getUserHome"in the browser then request will intercepted and control will be sending to the configured intercepter i.e., UserRequestInterceptor.

Please find the below given consolidated code for WebMvcConfig.java

WebMvcConfig.java
package com.docsconsole.tutorials.springmvc5.config;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

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

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.docsconsole.tutorials.springmvc5" })
public class WebMvcConfig implements WebMvcConfigurer {

	@Bean
	public InternalResourceViewResolver resolver() {
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setViewClass(JstlView.class);
		resolver.setPrefix("/WEB-INF/views/");
		resolver.setSuffix(".jsp");
		return resolver;
	}

	@Bean
	public MessageSource messageSource() {
		ResourceBundleMessageSource source = new ResourceBundleMessageSource();
		source.setBasename("messages");
		return source;
	}

	@Bean
	AdminRequestInterceptor gdminRequestInterceptor() {
		return new AdminRequestInterceptor();
	}

	@Bean
	UserRequestInterceptor userRequestInterceptor() {
		return new UserRequestInterceptor();
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(gdminRequestInterceptor()).addPathPatterns("/getAdminHome");
		registry.addInterceptor(userRequestInterceptor()).addPathPatterns("/getUserHome");
	}

}

Please find the below given classes for interceptors.

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());
	}
}

And we need to write JSP file for populating the model results.

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

To log messages in some log file we have to configure the log4j.properties as given below.

log4j.properties
# Root logger option

log4j.rootLogger=DEBUG, stdout, file


# Redirect log messages to console

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.Target=System.out

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

log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


# Redirect log messages to a log file

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

#outputs to Tomcat home

log4j.appender.file.File=${catalina.home}/logs/Spring5-MVC-HandlerInterceptor.log

log4j.appender.file.MaxFileSize=5MB

log4j.appender.file.MaxBackupIndex=10

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

log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Please find the below given diagram for final project architecture.

Spring5 MVC HandlerInterceptor JavaConfig Example

When you hit the URLs “http://localhost:8080/Spring5-MVC-HandlerInterceptor-JavaConfig-Example/getAdminHome” and “http://localhost:8080/Spring5-MVC-HandlerInterceptor-JavaConfig-Example/getUserHome” then you will get below given output in the tomcat console.

log messages in tomcat console
2018-12-08 20:26:29 INFO  AdminRequestInterceptor:15 - Request intercepted @preHandle-AdminRequestInterceptor
2018-12-08 20:26:29 INFO  AdminRequestInterceptor:16 - Request URL::http://localhost:8080/Spring5-MVC-HandlerInterceptor-JavaConfig-Example/getAdminHome
2018-12-08 20:26:29 INFO  HomeController:17 - Request @getAdminHome-HomeController
2018-12-08 20:26:29 INFO  HomeController:19 - Sending response @getAdminHome-HomeController
2018-12-08 20:26:29 INFO  AdminRequestInterceptor:24 - Request intercepted @postHandle-AdminRequestInterceptor
2018-12-08 20:26:29 INFO  AdminRequestInterceptor:25 - Request URL::http://localhost:8080/Spring5-MVC-HandlerInterceptor-JavaConfig-Example/getAdminHome
2018-12-08 20:26:29 INFO  AdminRequestInterceptor:31 - Request intercepted @afterCompletion-AdminRequestInterceptor
2018-12-08 20:26:29 INFO  AdminRequestInterceptor:32 - Request URL::http://localhost:8080/Spring5-MVC-HandlerInterceptor-JavaConfig-Example/getAdminHome

2018-12-08 20:26:40 INFO  UserRequestInterceptor:16 - Request intercepted @preHandle-UserRequestInterceptor
2018-12-08 20:26:40 INFO  UserRequestInterceptor:17 - Request URL::http://localhost:8080/Spring5-MVC-HandlerInterceptor-JavaConfig-Example/getUserHome
2018-12-08 20:26:40 INFO  HomeController:28 - Request @getUserHome-HomeController
2018-12-08 20:26:40 INFO  HomeController:30 - Sending response @getUserHome-HomeController
2018-12-08 20:26:40 INFO  UserRequestInterceptor:25 - Request intercepted @postHandle-UserRequestInterceptor
2018-12-08 20:26:40 INFO  UserRequestInterceptor:26 - Request URL::http://localhost:8080/Spring5-MVC-HandlerInterceptor-JavaConfig-Example/getUserHome
2018-12-08 20:26:42 INFO  UserRequestInterceptor:32 - Request intercepted @afterCompletion-UserRequestInterceptor
2018-12-08 20:26:42 INFO  UserRequestInterceptor:33 - Request URL::http://localhost:8080/Spring5-MVC-HandlerInterceptor-JavaConfig-Example/getUserHome

    Here HandlerAdapter will invoke handler methods as per order provided 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

Download Source Code Spring5-MVC-HandlerInterceptor-JavaConfig-Example.zip

Leave A Reply