springmvc 拦截器(springmvc教程六)
目录工程代码拦截器的使用多个拦截器的顺序工程代码github: https://github.com/dengjili/springmvc拦截器的使用定义一个拦截器public class MyInterceptor implements HandlerInterceptor {private static final Logger logger = LoggerFactory.g...
·
工程代码
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
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献3条内容
所有评论(0)