一般我们会做一些统一的操作这个时候我们需要使用springmvc提供的拦截器,例如token的验证,字段必填的操作,接口超时判断,签名验证,字段加密等操作,所以我们需要了解执行先后顺序。 我们来简单介绍下实现过程及对应代码,执行结果:
1、定义自己的spring mvc拦截器需要实现HandlerInterceptor 接口或者继承HandlerInterceptorAdapter
2、boolean preHandle()方法在controller被调用之前调用;
3、void postHandle()方法在controller被调用之后调用,可在modelandview中加入数据,比如当前时间;
4、void afterCompletion()在呈现视图之后调用,可用于清理资源等;
5、当设置多个拦截器时,先按顺序调用preHandle方法,然后逆序调用每个拦截器的postHandle和afterCompletion方法
public class MyInterceptor1 extends HandlerInterceptorAdapter {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("-------preHandle1-------");// 如果返回false,则不再调用之后的方法 return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("-------postHandle1-------");if (modelAndView != null) { // 当前时间 modelAndView.addObject("now", new Date());}}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("-------afterCompletion1-------");}}
public class MyInterceptor2 extends HandlerInterceptorAdapter {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("-------preHandle2-------");// 如果返回false,则不再调用之后的方法 return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("-------postHandle2-------");if (modelAndView != null) { // 加入当前时间 modelAndView.addObject("now", new Date());}}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("-------afterCompletion2-------");}}
<mvc:interceptors><mvc:interceptor><mvc:mapping path="/**"/><bean class="com.kingbal.web.interceptor.MyInterceptor1" /></mvc:interceptor><mvc:interceptor><mvc:mapping path="/**"/><bean class="com.kingbal.web.interceptor.MyInterceptor2" /></mvc:interceptor>
</mvc:interceptors>
会根据配置先后顺序往下执行,执行结果如下图 >>