springmvc 之 拦截器的实现(二)

来源:互联网 发布:算法设计与分析陈慧南 编辑:程序博客网 时间:2024/05/24 00:20

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 {@Overridepublic void afterCompletion(HttpServletRequest arg0,HttpServletResponse arg1, Object arg2, Exception arg3)throws Exception {System.out.println("执行到了afterCompletion方法!");}@Overridepublic void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,Object arg2, ModelAndView arg3) throws Exception {System.out.println("执行到了postHandle方法!");}@Overridepublic 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/mvchttp://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


1 0
原创粉丝点击