工程代码
github: https://github.com/dengjili/springmvc
拦截器的使用
定义一个拦截器
public class MyInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(MyController.class);
// 前置方法 若返回false,则直接结束
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
logger.debug("=>{}", "preHandle");
return true;
}
// 后置方法
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
logger.debug("=>{}", "postHandle");
}
// 视图结束后方法
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
logger.debug("=>{}", "afterCompletion");
}
}
配置拦截器
<!-- 拦截器配置 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/attribute/*" />
<bean class="priv.dengjl.interceptor.MyInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
多个拦截器的顺序
定义一个新拦截器
public class MyInterceptor2 implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(MyController.class);
// 前置方法 若返回false,则直接结束
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
logger.debug("=>{}", "preHandle2");
return true;
}
// 后置方法
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
logger.debug("=>{}", "postHandle2");
}
// 视图结束后方法
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
logger.debug("=>{}", "afterCompletion2");
}
}
配置拦截器
<!-- 拦截器配置 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/attribute/*" />
<bean class="priv.dengjl.interceptor.MyInterceptor" />
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/attribute/*" />
<bean class="priv.dengjl.interceptor.MyInterceptor2" />
</mvc:interceptor>
</mvc:interceptors>
输出结果
=>preHandle
=>preHandle2
=>postHandle2
=>postHandle
=>afterCompletion2
=>afterCompletion