必须实现HandlerInterceptor接口
接口中有3个方法 perHandle () postHandle() afterCompletion()
perHandle()是在处理请求之前调用的, 如果返回true ,执行下一个拦截器,直到所有的拦截器都执行完毕 再执行被拦截的Controller 然后进入拦截器链, 从最后一个拦截器往回执行所有的postHandle() 接着再从最后一个拦截器往回执行所有的afterCompletion() ,返回false ,从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
postHandle() 也就是Controller 方法调用之后执行,但是它会在DispatcherServlet 进行视图返回渲染之前被调用,所以我们可以在这个方法中对Controller 处理之后的ModelAndView 对象进行操作
afterCompletion() 方法,该方法也是需要当前对应的Interceptor 的preHandle 方法的返回值为true 时才会执行。顾名思义,该方法将在整个请求结束之后,也就是在DispatcherServlet 渲染了对应的视图之后执行。这个方法的主要作用是用于进行资源清理工作的。
把定义的拦截器类加到SpringMVC的拦截体系中
1.在SpringMVC的配置文件中加上支持MVC的schema
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation=" http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
下面是我的声明示例:
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
这样在SpringMVC的配置文件中就可以使用mvc标签了,mvc标签中有一个mvc:interceptors是用于声明SpringMVC的拦截器的。
(二)使用mvc:interceptors标签来声明需要加入到SpringMVC拦截器链中的拦截器
- <mvc:interceptors>
- <!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 -->
- <bean class="com.host.app.web.interceptor.AllInterceptor"/>
- <mvc:interceptor>
- <mvc:mapping path="/test/number.do"/>
- <!-- 定义在mvc:interceptor下面的表示是对特定的请求才进行拦截的 -->
- <bean class="com.host.app.web.interceptor.LoginInterceptor"/>
- </mvc:interceptor>
- </mvc:interceptors>
由上面的示例可以看出可以利用mvc:interceptors标签声明一系列的拦截器,然后它们就可以形成一个拦截器链,拦截器的执行顺序是按声明的先后顺序执行的,先声明的拦截器中的preHandle方法会先执行,然而它的postHandle方法和afterCompletion方法却会后执行。
在mvc:interceptors标签下声明interceptor主要有两种方式:
(1)直接定义一个Interceptor实现类的bean对象。使用这种方式声明的Interceptor拦截器将会对所有的请求进行拦截。
(2)使用mvc:interceptor标签进行声明。使用这种方式进行声明的Interceptor可以通过mvc:mapping子标签来定义需要进行拦截的请求路径。
经过上述两步之后,定义的拦截器就会发生作用对特定的请求进行拦截了。