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实现的,这种方式可 ...
随机推荐
- [ Java ] [ Eclipse ] 导出/导入Eclipse的workspace配置(备份Eclipse配置)
Export *.epf 文件 原文連結: http://www.cnblogs.com/52php/p/5677647.html
- 动态调用web服务 --WSHelper.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Net;us ...
- android开源项目---View篇
本文转载自:http://blog.csdn.net/likebamboo/article/details/19080739 主要介绍那些不错个性化的View,包括ListView.ActionBar ...
- 学习推荐《从Excel到Python数据分析进阶指南》高清中文版PDF
Excel是数据分析中最常用的工具,本书通过Python与Excel的功能对比介绍如何使用Python通过函数式编程完成Excel中的数据处理及分析工作.在Python中pandas库用于数据处理,我 ...
- CCF模拟题 字符串匹配
字符串匹配 时间限制: 1.0s 内存限制: 256.0MB 问题描述 给出一个字符串和多行文字,在这些文字中找到字符串出现的那些行.你的程序还需支持大小写敏感选项:当选项打开时,表示同一个字母的大写 ...
- js 图片轮转
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- Dynamics CRM2016 升级老版本号报“JavaScript Web 资源包括对 Microsoft Dynamics CRM 4.0 (2007) Web 服务终结点的引用”问题的解决的方法
今天在新的server上部署了CRM2016 on-premises,并将CRM2015的数据库拷贝过来准备附加后升级,但在升级过程中遇到了例如以下错误.向导检測到了我的JavaScript Web ...
- HDU - 2254 奥运 (求等比数列和)
Description 北京迎来了第一个奥运会,我们的欢呼声响彻中国大地,所以今年的奥运金牌 day day up! 比尔盖兹坐上鸟巢里,手里摇着小纸扇,看的不亦乐乎,被俺们健儿的顽强拼搏的精神深深的 ...
- jquery16 DOM操作 : 添加 删除 获取 包装 DOM筛选
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...
- 在英语中,in,on,at的用法是?
在几点:at xx:xx ,在那月: in Dec./Jan.……, 在那日:on Thur./Mon.……,on Jan. 16th 时间前面 at, 年月日前面如果有具体的日子,就是具体的哪一天 ...