import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
/*preHandler方法会[早于]控制器中的方法先执行
如果该方法返回false,则不执行控制器的方法(相当于之前没有执行放行代码)
返回true,则继续执行控制器的方法
* */
@Override
public boolean preHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o) throws Exception {
System.out.println("MyInterceptor的preHandler方法被执行了");
return true;
}
/*
* postHandle方法[晚于]控制器方法执行-1
* 控制器方法执行完,在准备跳转页面之前,先执行该方法,此时ModelAndView中存储着控制器要跳转的页面路径和
* 存储作用域数据*/
@Override
public void postHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, ModelAndView modelAndView) throws Exception {
System.out.println("MyInterceptor的postHandle方法被执行了");
}
/*afterCompletion
* 方法[晚于]控制器方法执行-2
* 等页面跳转渲染了才会执行*/
@Override
public void afterCompletion(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, Exception e) throws Exception {
System.out.println("MyInterceptor的afterCompletion方法执行了");
}
}
<!--拦截器相关配置-->
<mvc:interceptors>
<mvc:interceptor>
<!--指定要拦截器的请求路径
/* 只能拦截器http://ip地址:8081/项目名/test3.do请求
/** 拦截所有请求
-->
<mvc:mapping path="/**"/>
<!--exclude(排除)排除一些不拦截的请求路径
<mvc:mapping path=""/>
-->
<!--拦截器的全类名-->
<bean class="com.test.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
原文:https://www.cnblogs.com/huahualove/p/13626938.html