自定义拦截器
1. 自定义的拦截器实现HandlerInterceptor接口
public class FirstInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("firstInterceptor->afterCompletion");
}
/* 渲染视图后调用*/
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
System.out.println("firstInterceptor->postHandle");
}
/* 目标方法执行后调用
* 但是此时还没有渲染视图*/
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
System.out.println("firstInterceptor->preHandle");
return true;
}
/* 目标方法执行前调用 :
* 如果返回false,那么将不再继续*/
}
2. 在springmvc中配置拦截器
<mvc:interceptors>
<bean class="interceptor.FirstInterceptor"></bean>
<!-- 配置(不)拦截的路径 -->
<mvc:interceptor>
<mvc:mapping path="/testInterceptor"/><!-- secondInterceptor拦截的路径 -->
<mvc:exclude-mapping path="/other"/><!-- secondInterceptor不拦截的路径 -->
<bean class="interceptor.SecondInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
3. 拦截器的执行顺序
firstInterceptor->preHandle
secondInterceptor->preHandle
testInterceptor
secondInterceptor->postHandle
firstInterceptor->postHandle
secondInterceptor->afterCompletion
firstInterceptor->afterCompletion
如果某个preHandle方法返回了false,那么其后面的方法都没有机会再执行,除了比该拦截器优先级高的afterCompletion方法除外