1、Spring MVC 的拦截器类似于Servlet 开发中的过滤器Filter,用于对Controller进行预处理和后处理。
2、使用SpringMVC拦截器步骤:
1.定义拦截器类
1.1 实现接口 org.springframework.web.servlet.HandlerInterceptor
1.2 继承适配器:org.springframework.web.servlet.handler.HandlerInterceptorAdapter
public class MyInterceptor implements HandlerInterceptor { @Override//前置拦截 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle"); return true; } @Override//后置拦截 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle"); } @Override//最终拦截,视图渲染之后 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("after.........."); } }
public class MyInterceptor2 extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("pre2....."); return super.preHandle(request, response, handler); } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("post2----------"); super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("after2-------"); super.afterCompletion(request, response, handler, ex); } }
2.在applicationContext.xml中配置拦截器
<!--配置拦截器--> <mvc:interceptors> <mvc:interceptor> <!--拦截什么样的路径 /*:表示拦截所有的一级路径,此时如果是二级路径则不经过拦截器 /**:表示拦截任意多级路径 /student/get/list/query --> <mvc:mapping path="/**"/> <!--排除哪个路径,表示这个路径不再经过拦截器--> <mvc:exclude-mapping path="/*/list"/> <!--拦截器的全限定名--> <bean class="com.test._06_interceptor.MyInterceptor"/> </mvc:interceptor> <mvc:interceptor> <!--拦截什么样的路径--> <mvc:mapping path="/**"/> <!--拦截器的全限定名--> <bean class="com.test._06_interceptor.MyInterceptor2"/> </mvc:interceptor> </mvc:interceptors>
3、拦截器方法的执行时机:
1.preHandle:控制器方法执行之前执行,返回结果为true表示放行;如果返回为false,表示拦截(可以做权限拦截,登录检查拦截)。
2.postHandle:控制器方法执行后,视图渲染之前执行(可以加入统一的响应信息)。
3.afterCompletion:视图渲染之后执行(处理Controller异常信息,记录操作日志,清理资源等)。