Interceptors are used to intercept the request.
Example 1:
You may want to preprocess the input before handing it over to actual controller class.
Example 2:
You may want to calculate the execution time of the request. You can do that by using interceptors.
How to create an interceptor?
There are two ways.
a. By implementing org.springframework.web.servlet.HandlerInterceptor interface interface
b. By extending the class org.springframework.web.servlet.handler.HandlerInterceptorAdapter
HandlerInterceptor interface
HandlerInterceptor interface provides below three methods.
default boolean preHandle(HttpServletRequest request, Httpservletresponse Response, Object handler)throws Exception
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception
This method is called before the request is handed over to the handler method. This method should return true if the execution chain should proceed with the next interceptor or the handler itself. Else, DispatcherServlet assumes that this interceptor has already dealt with the response itself.
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception
Called after HandlerAdapter actually invoked the handler, but before the DispatcherServlet renders the view.
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception
Callback after completion of request processing, that is, after rendering the view.
You need to register the interceptor in dispatcher servlet like below.
Find the below working application.
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"%>
http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
Hello World Spring Web MVC
${message}
${message}
/>
Execution Time : ${executionTime} nanoseconds
/>
Create web.xml, HelloWorld-servlet.xml files under WEB-INF folder.
web.xml
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">Spring MVC Hello WorldApplication HelloWorld org.springframework.web.servlet.DispatcherServlet 1 HelloWorld /
HelloWorld-servlet.xml
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">/>
base-package="com.sample.myApp" />
class="org.springframework.web.servlet.view.InternalResourceViewResolver">name="prefix" value="/WEB-INF/jsp/" /> name="suffix" value=".jsp" /> class="com.sample.myApp.interceptors.PerformanceReportInterceptor" />
Create index.jsp file under webapp folder.
index.jsp
taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
Welcome Page
Click on below button to get welcome page
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
This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here