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实现的,这种方式可 ...
随机推荐
- 对比《动手学深度学习》 PDF代码+《神经网络与深度学习 》PDF
随着AlphaGo与李世石大战的落幕,人工智能成为话题焦点.AlphaGo背后的工作原理"深度学习"也跳入大众的视野.什么是深度学习,什么是神经网络,为何一段程序在精密的围棋大赛中 ...
- 学习推荐《Python神经网络编程》中文版PDF+英文版PDF+源代码
推荐非常适合入门神经网络编程的一本书<Python神经网络编程>,主要是三部分: 介绍神经网络的基本原理和知识:用Python写一个神经网络训练识别手写数字:对识别手写数字的程序的一些优化 ...
- CMDB学习之七-实现采集错误捕捉,日志信息处理
首先采集disk的具体实现方上代码: # !/usr/bin/env python # -*- coding:utf-8 -*- from .base import BasePlugin import ...
- EditPlus 使用技巧以及快捷键
一边阅读,一边动手吧! 为了达到更好的效果,请你先下载我打包的这个 EditPlus压缩包文件(压缩包文件为绿色的EditPlus2.31英文版,含自动完成文件,高亮语法文件和剪切板代码片断文件,这些 ...
- 游戏开发之UDK引擎介绍和模型导入
2014-09-18 10:01:3 3.7.5" style="border:0px; vertical-align:middle; max-width:100%"&g ...
- js --- return返回值 闭包
什么是闭包?这就是闭包! 有权访问另一个函数作用域内变量的函数都是闭包.这里 inc 函数访问了构造函数 a 里面的变量 n,所以形成了一个闭包. function a(){ var n = 0; f ...
- 浏览器加载渲染HTML、DOM、CSS、 JAVASCRIPT、IMAGE、FLASH、IFRAME、SRC属性等资源的顺序总结
页面响应加载的顺序: 1.域名解析->加载html->加载js和css->加载图片等其他信息 DOM详细的步骤如下: 解析HTML结构. 加载外部脚本和样式表文件. 解析并执行脚 ...
- 带你底层看Sqoop如何转换成MapReduce作业运行的(代码程序)
补充 其实啊,我们知道,sqoop在运行的时候,最终会去转换成mapreduce作业,这个很简单,不多赘述.直接贴出来. 具体这些怎么运行的,见我如下这篇博客.这里只做一个引子. Sqoop Impo ...
- mysql查询最新一组数据
public function getDetail(){ $sql = "SELECT * FROM (SELECT * FROM Z_CFTC_GOV_NEW ORDER BY UPDAT ...
- newgrp---将当前登录用户临时加入到已有的组中
Linux中的newgrp命令主要是将当前登录用户临时加入到已有的组中,用法如下: [linuxidc@localhost etc]$ newgrp grptest 上面命令的含义是将用户linuxi ...