Spring MVC handler interceptors example--转载
原文地址:http://www.mkyong.com/spring-mvc/spring-mvc-handler-interceptors-example/
Spring MVC allow you to intercept web request through handler interceptors. The handler interceptor have to implement the HandlerInterceptor interface, which contains three methods :
- preHandle() – Called before the handler execution, returns a boolean value, “true” : continue the handler execution chain; “false”, stop the execution chain and return it.
- postHandle() – Called after the handler execution, allow manipulate the ModelAndView object before render it to view page.
- afterCompletion() – Called after the complete request has finished. Seldom use, cant find any use case.
In this tutorial, you will create two handler interceptors to show the use of the HandlerInterceptor.
- ExecuteTimeInterceptor – Intercept the web request, and log the controller execution time.
- MaintenanceInterceptor – Intercept the web request, check if the current time is in between the maintenance time, if yes then redirect it to maintenance page.
It’s recommended to extend the HandlerInterceptorAdapter for the convenient default implementations.
1. ExecuteTimeInterceptor
Intercept the before and after controller execution, log the start and end of the execution time, save it into the existing intercepted controller’s modelAndView for later display.
File : ExecuteTimeInterceptor.java
package com.mkyong.common.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 ExecuteTimeInterceptor extends HandlerInterceptorAdapter{ private static final Logger logger = Logger.getLogger(ExecuteTimeInterceptor.class); //before the actual handler will be executed
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler)
throws Exception { long startTime = System.currentTimeMillis();
request.setAttribute("startTime", startTime); return true;
} //after the handler is executed
public void postHandle(
HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView)
throws Exception { long startTime = (Long)request.getAttribute("startTime"); long endTime = System.currentTimeMillis(); long executeTime = endTime - startTime; //modified the exisitng modelAndView
modelAndView.addObject("executeTime",executeTime); //log it
if(logger.isDebugEnabled()){
logger.debug("[" + handler + "] executeTime : " + executeTime + "ms");
}
}
}
2. MaintenanceInterceptor
Intercept before the controller execution, check if the current time is in between the maintenance time, if yes then redirect it to maintenance page; else continue the execution chain.
File : MaintenanceInterceptor.java
package com.mkyong.common.interceptor; import java.util.Calendar; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class MaintenanceInterceptor extends HandlerInterceptorAdapter{ private int maintenanceStartTime;
private int maintenanceEndTime;
private String maintenanceMapping; public void setMaintenanceMapping(String maintenanceMapping) {
this.maintenanceMapping = maintenanceMapping;
} public void setMaintenanceStartTime(int maintenanceStartTime) {
this.maintenanceStartTime = maintenanceStartTime;
} public void setMaintenanceEndTime(int maintenanceEndTime) {
this.maintenanceEndTime = maintenanceEndTime;
} //before the actual handler will be executed
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler)
throws Exception { Calendar cal = Calendar.getInstance();
int hour = cal.get(cal.HOUR_OF_DAY); if (hour >= maintenanceStartTime && hour <= maintenanceEndTime) {
//maintenance time, send to maintenance page
response.sendRedirect(maintenanceMapping);
return false;
} else {
return true;
} }
}
3. Enable the handler interceptor
To enable it, put your handler interceptor class in the handler mapping "interceptors" property.
<beans xmlns="http://www.springframework.org/schema/beans"
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-2.5.xsd"> <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/welcome.htm">welcomeController</prop>
</props>
</property>
<property name="interceptors">
<list>
<ref bean="maintenanceInterceptor" />
<ref bean="executeTimeInterceptor" />
</list>
</property>
</bean> <bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<property name="interceptors">
<list>
<ref bean="executeTimeInterceptor" />
</list>
</property>
</bean> <bean id="welcomeController"
class="com.mkyong.common.controller.WelcomeController" />
<bean class="com.mkyong.common.controller.MaintenanceController" /> <bean id="executeTimeInterceptor"
class="com.mkyong.common.interceptor.ExecuteTimeInterceptor" /> <bean id="maintenanceInterceptor"
class="com.mkyong.common.interceptor.MaintenanceInterceptor">
<property name="maintenanceStartTime" value="23" />
<property name="maintenanceEndTime" value="24" />
<property name="maintenanceMapping" value="/SpringMVC/maintenance.htm" />
</bean> <bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean> </beans>
Spring MVC handler interceptors example--转载的更多相关文章
- spring mvc handler的三种方式
springmvc.xml 三种方式不能针对一个controller同时使用 <?xml version="1.0" encoding="UTF-8"?& ...
- 【Java Web开发学习】Spring MVC 拦截器HandlerInterceptor
[Java Web开发学习]Spring MVC 拦截器HandlerInterceptor 转载:https://www.cnblogs.com/yangchongxing/p/9324119.ht ...
- SpringMVC(八):使用Servlet原生API作为Spring MVC hanlder方法的参数
在SpringMVC开发中,是有场景需要在Handler方法中直接使用ServletAPI. 在Spring MVC Handler的方法中都支持哪些Servlet API作为参数呢? --Respo ...
- Posting JSON to Spring MVC Controller
Spring MVC can be setup to automatically bind incoming JSON string into a Java object. Firstly, ensu ...
- 【Java Web开发学习】Spring MVC 使用HTTP信息转换器
[Java Web开发学习]Spring MVC 使用HTTP信息转换器 转载:https://www.cnblogs.com/yangchongxing/p/10186429.html @Respo ...
- 【Java Web开发学习】Spring MVC文件上传
[Java Web开发学习]Spring MVC文件上传 转载:https://www.cnblogs.com/yangchongxing/p/9290489.html 文件上传有两种实现方式,都比较 ...
- spring mvc入门教程 转载自【http://elf8848.iteye.com/blog/875830】
目录 一.前言二.spring mvc 核心类与接口三.spring mvc 核心流程图 四.spring mvc DispatcherServlet说明 五.spring mvc 父子上下文的说明 ...
- 转载:深入理解Spring MVC 思想
原文作者:赵磊 原文地址:http://elf8848.iteye.com/blog/875830 目录 一.前言二.spring mvc 核心类与接口三.spring mvc 核心流程图 四.sp ...
- Spring MVC 中 HandlerInterceptorAdapter的使用--转载
原文地址:http://blog.csdn.net/liuwenbo0920/article/details/7283757 一般情况下,对来自浏览器的请求的拦截,是利用Filter实现的,这种方式可 ...
随机推荐
- refresh table tablename ;MSCK REPAIR TABLE table_name;
在更改分区内的文件后刷新表 refresh table tablename ; 我们平时通常是通过alter table add partition方式增加Hive的分区的,但有时候会通过HDFS p ...
- AIX 压缩与归档
.tar.Z 格式 压缩: compress filename.tar 解压: zcat filename.tar.Z tar -xvf - .tar.gz 格式 压缩:t ...
- C#解决System.Security.Cryptography.MD5.Create()调用的目标发生了异常)的问题
今天搭建微信扫码支付环境的时候,一样的配置参数,调用连接提示错误 错误:调用的目标发生了异常 然后跟踪到执行 MD5 md5 = System.Security.Cryptography.MD5.Cr ...
- Cisco路由器交换机配置命令详解
1. 交换机支持的命令: 交换机基本状态:switch: :ROM状态, 路由器是rommon>hostname> :用户模式hostname# :特权模式hostname(config) ...
- Swift学习笔记(1)--基本语法
1.分号; 1>Swift不要求每个语句后面跟一个分号作为语句结束的标识,如果加上也可以,看个人喜好 2>在一行中写了两句执行语句,需要用分号隔开,比如 let x = 0; printl ...
- 具体解释NoSQL数据库使用实例
一.NoSQL基础知识 1.关于NoSQL 在"NoSQL"一词.实际上是一个叫Racker的同事创造的,当约翰埃文斯埃里克要组织一次活动来讨论开源的分布式数据库. 这个名称和概念 ...
- spring源码分析之@Conditional
根源在AnnotationConfigApplicationContext和AnnotationConfigWebApplicationContext,以AnnotationConfigApplica ...
- 小米开源文件管理器MiCodeFileExplorer-源码研究(9)-入口分析
AndroidManifest.xml是Android应用程序最重要的配置文件. 入口文件和intent-filter <application android:icon="@draw ...
- golang 数组
数组是Go语言编程中最常用的数据结构之一.顾名思义,数组就是指一系列同一类型数据的集合.数组中包含的每个数据被称为数组元素(element),一个数组包含的元素个数被称为数组的长度. 在Go语言中数组 ...
- ORA-01653 无法在表空间扩展的解决办法 -- 增加表空间大小或给表空间增加数据文件
转自原文 ORA-01653 无法在表空间扩展的解决办法 -- 增加表空间大小或给表空间增加数据文件 当前系统的数据量越来越大的,昨天还运行正常的数据库,突然无法使用了.经过定位发现是"OR ...