Saturday 1 December 2018

Spring mvc: Mapping urls to interceptors

This is continuation to my previous post. In my previous post, I explained how to intercept a request. In this post, I am going to show you how to map a url to an interceptor.

It is very simple, add below lines in dispatcher servlet.

         <mvc:interceptors>
                  <mvc:interceptor>
                           <mvc:mapping path="/welcome" />
                           <bean class="com.sample.myApp.interceptors.PerformanceReportInterceptor" />
                  </mvc:interceptor>
         </mvc:interceptors>
        
As you see above snippet, I mapped the url /welcome to PerformanceReportInterceptor. PerformanceReportInterceptor is not been invoked for any other requests.

Find the below working application.

HelloWorldController.java
package com.sample.myApp.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {

 @RequestMapping("/welcome")
 public ModelAndView getHelloMessage() {

  ModelAndView modelAndView = new ModelAndView("welcome");

  modelAndView.addObject("message", "Dear User, Good Morning");

  return modelAndView;
 }

}


I defined an interceptor that is used to calculate the exection time of the request.

PerformanceReportInterceptor.java
package com.sample.myApp.interceptors;

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

import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class PerformanceReportInterceptor implements HandlerInterceptor {

 private long startTime;

 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
   throws Exception {
  startTime = System.nanoTime();
  return true;

 }

 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
   @Nullable ModelAndView modelAndView) throws Exception {
  long executionTime = System.nanoTime() - startTime;
  modelAndView.addObject("executionTime", executionTime);
 }
}

Create welcome.jsp file under WEB-INF/jsp folder.


welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World Spring Web MVC</title>
</head>
<body>
 <h1>${message}</h1>

 <h3>
  ${message} <br /> 
  Execution Time : ${executionTime} nanoseconds<br />
 </h3>
</body>
</html>

Create web.xml, HelloWorld-servlet.xml files under WEB-INF folder.


web.xml
<web-app id="WebApp_ID" version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <display-name>Spring MVC Hello WorldApplication</display-name>

 <servlet>
  <servlet-name>HelloWorld</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>HelloWorld</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>

HelloWorld-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 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-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

 <mvc:annotation-driven />

 <context:component-scan
  base-package="com.sample.myApp" />

 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
 </bean>

 <mvc:interceptors>
  <mvc:interceptor>
   <mvc:mapping path="/welcome" />
   <bean class="com.sample.myApp.interceptors.PerformanceReportInterceptor" />
  </mvc:interceptor>
 </mvc:interceptors>

</beans>

Create index.jsp file under webapp folder.


index.jsp
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Welcome Page</title>
</head>

<body>
 <h2>Click on below button to get welcome page</h2>
 <form method="post" action="/springdemo/welcome" id="f1">
  <input type="submit" name="submit" value="submit"
   style="font-size: 18px;" />
 </form>
</body>
</html>

Project structure looks like below.
Run the application on server. You can able to see below screen.
Click on submit button, you can able to see below screen.




Previous                                                 Next                                                 Home

No comments:

Post a Comment