本文转自http://www.cnblogs.com/fangjian0423/p/springMVC-interceptor.html 感谢作者
目录
前言
SpringMVC是目前主流的Web MVC框架之一。
拦截器是每个Web框架必备的功能,也是个老生常谈的主题了。
本文将分析SpringMVC的拦截器功能是如何设计的,让读者了解该功能设计的原理。
重要接口及类介绍
1. HandlerExecutionChain类
由HandlerMethod和Interceptor集合组成的类,会被HandlerMapping接口的getHandler方法获取。
2. HandlerInterceptor接口
SpringMVC拦截器基础接口。
3. AbstractHandlerMapping
HandlerMapping的基础抽象类。
4. AsyncHandlerInterceptor
继承HandlerInterceptor的接口,额外提供了afterConcurrentHandlingStarted方法,该方法是用来处理异步请求。当Controller中有异步请求方法的时候会触发该方法。 楼主做过测试,异步请求先支持preHandle、然后执行afterConcurrentHandlingStarted。异步线程完成之后执行preHandle、postHandle、afterCompletion。 有兴趣的读者可自行研究。
5. HandlerInterceptorAdapter
实现AsyncHandlerInterceptor接口的抽象类,一般我们使用拦截器的话都会继承这个类。然后复写相应的方法。
6. WebRequestInterceptor
与HandlerInterceptor接口类似,区别是WebRequestInterceptor的preHandle没有返回值。还有WebRequestInterceptor是针对请求的,接口方法参数中没有response。
AbstractHandlerMapping内部的interceptors是个Object类型集合。处理的时候判断为MappedInterceptor[加入到mappedInterceptors集合中];Han