springmvc的拦截器interceptpr相当于servlet的过滤器filter
按顺序联结 形成拦截器链
步骤:
1.创建拦截器实现handleinterceptor接口
package com.itheima.intercept; import org.springframework.lang.Nullable; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyIntercept implements HandlerInterceptor { //目标方法执行之前 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle..."); return true; } //目标方法执行后、视图对象返回前 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { System.out.println("postHandle..."); } //整个流程执行完毕后 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { System.out.println("afterCompletion..."); } }
2.配置拦截器
<mvc:interceptors> <mvc:interceptor> <!--对哪些资源执行--> <mvc:mapping path="/**"/> <bean class="com.itheima.intercept.MyIntercept"/> </mvc:interceptor> </mvc:interceptors>
3.测试拦截器效果