您的位置:首页 > 编程语言 > Java开发

springmvc 之 拦截器的实现(二)

2016-01-19 16:28 447 查看
1.编写拦截器类实现: HandlerInterceptor接口

新建一个 Test1Interceptor.java类

<span style="font-size:18px;">package com.lee.springmvc.interceptor;

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

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

/***
* 设置拦截器(在 applicationContext-config.xml 中配置 注册到配置文件中)
* @author liyintao
*
*/
public class Test1Interceptor implements HandlerInterceptor {

@Override
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("执行到了afterCompletion方法!");
}

@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
System.out.println("执行到了postHandle方法!");
}

@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
System.out.println("执行到了preHandle方法!");
return true;//暂时先改为true
}

}
</span>


2.强拦截器注册进SpringMVC框架中

在配置文件中添加:

<span style="font-size:18px;">xmlns:mvc="http://www.springframework.org/schema/mvc" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
</span>


<span style="font-size:18px;"><!-- 注册拦截器:需要用到mvc标签,故要引用这个地址命名空间
xmlns:mvc="http://www.springframework.org/sechema/mvc" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
-->
<mvc:interceptors>
<bean class="com.lee.springmvc.interceptor.Test1Interceptor"></bean>
</mvc:interceptors></span>


3.配置拦截器的拦截规则

在配置文件的mvc标签修改(用  .do   是因为在web.xml中配置 是 */do)

这样只有调用这个方法的时候才调用拦截器

登录对应方Controller
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: