第一步:新建拦截器类,可以建多个,继承HandlerInterceptor接口,实现preHandle();postHandle();afterCompletion()三个方法.
preHandle() 方法:该方法会在控制器方法前执行,其返回值表示是否中断后续操作。当其返回值为true时,表示 继续向下执行;当其返回值为false时,会中断后续的所有操作(包括调用下一个拦截器和控制器类中的方法执行等)。
postHandle()方法:该方法会在控制器方法调用之后,且解析视图之前执行。可以通过此方法对请求域中的模型和视图做出进一步的修改。
afterCompletion()方法:该方法会在整个请求完成,即视图渲染结束之后执行。可以通过此方法实现一些资源释放、记录日志信息等工作。
public class Interceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println("Interceptor-preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("Interceptor-postHandle");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("Interceptor-afterCompletion");
}
}
public class DetailInterceptor implements HandlerInterceptor {
//请求之前执行的方法,也就是controller之前执行,多用于编码,安全处理,逻辑控制
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println("DetailInterceptor-preHandle");
return true;
}
//在controller生成视图之前执行,可以修该ModelAndView对象
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("DetailInterceptor-postHandle");
}
//在响应已经渲染之后执行,用于释放资源
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("DetailInterceptor-afterCompletion");
}
}
第二步:配置文件配置
<!--拦截器,新建拦截器类,继承HandlerInterceptor接口,实现方法-->
<!--可以配置多个-->
<mvc:interceptors>
<mvc:interceptor>
<!--表示匹配指定路径的请求才进行拦截,拦截detail开头的所有路径-->
<mvc:mapping path="/detail/*"/>
<bean class="cn.kgc.myinterceptor.DetailInterceptor"/>
</mvc:interceptor>
<mvc:interceptor>
<!--表示匹配指定路径的请求才进行拦截,拦截所有路径-->
<mvc:mapping path="/**"/>
<bean class="cn.kgc.myinterceptor.Interceptor"/>
</mvc:interceptor>
</mvc:interceptors>
|
|