每天学点SpringMVC-拦截器
1. 先写个Hello World
1.1 写一个Interceptor class并实现HandlerInterceptor接口
public class FirstInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { System.out.println("FirstInterceptor,preHandle"); return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("FirstInterceptor,postHandle"); } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { System.out.println("FirstInterceptor,afterCompletion"); } }
1.2 spring-mvc.xml配置
<mvc:interceptors> <bean class="com.pawn.crud.web.interceptors.FirstInterceptor"/> </mvc:interceptors>
1.3 访问任意目标方法 测试日志如下
FirstInterceptor,preHandle
FirstInterceptor,postHandle
FirstInterceptor,afterCompletion
1.4 HandlerInterceptor接口一共有三个方法
1)preHandler:该方法会在目标方法执行之前执行,一般用于事物,日志,权限等处理,另外返回结果为false时,会拦截之后的拦截器以及目标方法,请求就此终止
2)postHandler:该方法会在目标方法执行之后,渲染视图之前执行,一般用于对将要进行视图渲染的属性和参数进行修改
3)afterCompletion:该方法会在视图渲染之后执行,一般用于资源释放
2. 拦截器可配置只对某个目录进行拦截或不拦截
<mvc:interceptor> <mvc:mapping path="/test"/> <!--<mvc:exclude-mapping path="/emps"/>-->
<bean class="com.pawn.crud.web.interceptors.FirstInterceptor"/> </mvc:interceptor>
3. 多个拦截器的执行顺序
注意:当其中某个拦截器的preHandler返回false时,该拦截器的之前的拦截器们还是会被执行的
demo:https://github.com/705645051/demoCrud