6.4.3  拦截器执行规则

更新于 2026年10月13日 版权声明
6.4.3 拦截器执行规则

接下来通过定义两个拦截器来观察拦截器的执行规则,定义拦截器HandlerInterceptor1和HandlerInterceptor2,两个类具体内容大致相同,都是在方法执行时打印自己的拦截器名称加方法名。HandlerInterceptor1具体如下:

图示

图示

HandlerInterceptor2具体如下:

图示

然后在spring-servlet.xml文件中配置此拦截器。具体如下:

图示

图示

这里HandlerInterceptor1和HandlerInterceptor2两个拦截器的拦截路径规则配置一致。请求之前定义的页面,控制台输出如下信息:

HandlerInterceptor1...preHandle

HandlerInterceptor2--->preHandle(https://www.daowen.com)

getProductInfo()called with:proId=[107]

HandlerInterceptor2--->postHandle

HandlerInterceptor1...postHandle

HandlerInterceptor2--->afterCompletion

HandlerInterceptor1...afterCompletion

可以自行设置拦截器方法返回的拦截标志true(放行)或者false(不放行),得出如下规律:

■拦截器1放行,拦截器2 preHandle才会执行。

■拦截器2 preHandle不放行,拦截器2 postHandle和afterCompletion不会执行。

■只要有一个拦截器不放行,postHandle都不会执行。

✍AI写作