疑问:request请求是怎样find对应的controller
两种方法: 1、通过DispatcherServlet debug request的处理过程;
2、Insight spring-webmvc HandlerMapping 初始化过程。
本文通过方法2 Insight 初始化过程,解答find handler/request机制:
/**
* HandlerMapping 实现核心Class
* 核心属性urlMap (request/HanlderMethod)
*/
public abstract class AbstractHandlerMethodMapping
implements InitializingBean {
/**
* Spring bean 初始化入口,Detects handler methods at initialization.
* 1.Scan beans in the ApplicationContext(scan 的范围是context所有的bean),
* 2.detect and register handler methods(detect实现参考 RequestMappingHandlerMapping.isHandler()).
*/
public void afterPropertiesSet() {
initHandlerMethods();
}
/**
* Register a handler method and its unique mapping.
* 最终会构造mapping: handlerMethods = (mapping : HandlerMethod(handler, method)), urlMap = (url : mapping)
*/
protected void registerHandlerMethod(Object handler, Method method, T mapping) {
HandlerMethod newHandlerMethod = createHandlerMethod(handler, method);
// ...
this.handlerMethods.put(mapping, newHandlerMethod);
// ...
Set
patterns = getMappingPathPatterns(mapping);
for (String pattern : patterns) {
if (!getPathMatcher().isPattern(pattern)) {
this.urlMap.add(pattern, mapping);
}
}
}
}/**
* @Controller, @RequestMapping 注解HandlerMapping实现
* extends AbstractHandlerMethodMapping
*/
public class RequestMappingHandlerMapping ... {
/**
* Whether the given type is a handler with handler methods.
* Expects a handler to have a type-level @{@link Controller} annotation.
*/
@Override
protected boolean isHandler(Class
beanType) {
return ((AnnotationUtils.findAnnotation(beanType, Controller.class) != null) ||
(AnnotationUtils.findAnnotation(beanType, RequestMapping.class) != null));
}
}
mvc-context分发request请求,根据url find mappingInfo, 然后根据mappingInfo find 对应的handler.method()。