Spring MVC 拦截器
在Spring MVC的配置文件中配置拦截器(这里配置了两个拦截器)
<!-- 配置拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 配置要拦截的请求 -->
<mvc:mapping path="/*"/>
<!-- 配置自定义的拦截器 -->
<bean class="com.zgz.springmvc.interceptors.FirstInterceptor"></bean>
</mvc:interceptor>
<mvc:interceptor>
<!-- 配置多个拦截器 -->
<mvc:mapping path="/*"/>
<bean class="com.zgz.springmvc.interceptors.SecondInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
拦截器必须实现HandlerInterceptor接口,该接口定义了三个方法,掌握这三个方法的作用和有多个拦截器时的执行过程即可
多个拦截器时的执行流程图
两个拦截器
public class FirstInterceptor implements HandlerInterceptor {
/**
* 该方法在目标方法之前调用
* 若该方法返回值为true,则继续调用后续的拦截器和目标方法
* 若返回值为false,则不会调用后续的拦截器和目标方法
*
* 可以考虑做权限,日志,事务等
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
System.out.println("preHandle: ");
return true;
}
/**
* 调用目标方法之后,但在渲染视图之前
* 可以对请求域中的属性或视图做出修改
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
System.out.println("postHandle: ");
}
/***
* 渲染试图之后被调用
* 可以释放资源
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("afterCompletion: ");
}
}
public class SecondInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
System.out.println("preHandle2: ");
return true;
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
System.out.println("postHandle2: ");
}
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("afterCompletion2: ");
}
}
执行结果
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。