在定义拦截器时需要实现HandlerInterceptor
后通过接口中的方法去实现即可
(1)实现接口Interceptor
的MyInterceptor
类
public class MyInterceptor implements HandlerInterceptor {
/**
* 在处理器处理具体方法之前开始执行
* @param request
* @param response
* @param handler
* @return 注意返回值,若返回值是false表示请求处理到此为止,如果是true,才会向下执行
* @throws Exception
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println(this.getClass().getName()+"拦截器开始执行");
//当为true时才会继续执行,如果为false会不再执行后面部分
return true;
}
/**
* 在处理器完成方法的处理之后执行
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println(this.getClass().getName());
}
/**
* 整个servlet处理完成之后才会执行,主要做资源清理的工作
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println(this.getClass().getName());
}
}
(2)xml文件配置,开启拦截器
<mvc:interceptors>
<bean class="com.csh.interceptor.MyInterceptor"></bean>
</mvc:interceptors>
(3)请求的使用,其实定义的拦截器在任何请求中都会调用到,所以这里的Controller并没有什么特殊,普通的请求及返回跳转
@Controller
public class InterceptorController {
@RequestMapping("/testinterceptor")
public String interceptor(){
System.out.println(this.getClass().getName());
return "success";
}
}
执行顺序:
preHandle—》目标的方法—》postHandle----》先页面跳转----》afterCompletion
如果执行报异常,那么afterCompletion依然会继续执行
当有多个拦截器时,执行顺序是按照先都执行preHandle后逆序回来执行postHandle