原文链接:https://blog.csdn.net/qq_38410730/article/details/79507465
Spring MVC的Control主要由HandlerMapping和HandlerAdapter两个组件提供。HandlerMapping负责映射用户的URL和对应的处理类,HandlerMapping并没有规定这个URL与应用的处理类如何映射,在HandlerMapping接口中只定义了根据一个URL必须返回一个由HandlerExecutionChain代表的处理链,我们可以在这个处理链中添加任意的HandlerAdapter实例来处理这个URL对应的请求。
HandlerMapping类相关的结构图
HandlerMapping的初始化程序
Spring MVC提供了许多HandlerMapping的实现,默认使用的是BeanNameUrlHandlerMapping,可以根据Bean的name属性映射到URL中。同时,我们可以为DispatcherServlet提供多个HandlerMapping供其使用。DispatcherServlet在选用HandlerMapping的过程中,将根据我们指定的一系列HandlerMapping的优先级进行排序,然后优先使用优先级高的HandlerMapping。
private void initHandlerMappings(ApplicationContext context) {
this.handlerMappings = null;
if (this.detectAllHandlerMappings) {
// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
Map<String, HandlerMapping> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());
// We keep HandlerMappings in sorted order.
OrderComparator.sort(this.handlerMappings);
}
}
else {
try {
HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
this.handlerMappings = Collections.singletonList(hm);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default HandlerMapping later.
}
}
// Ensure we have at least one HandlerMapping, by registering
// a default HandlerMapping if no other mappings are found.
if (this.handlerMappings == null) {
this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
if (logger.isDebugEnabled()) {
logger.debug("No HandlerMappings found in servlet '" + getServletName() + "': using default");
}
}
}
默认情况下,Spring MVC会加载在当前系统中所有实现了HandlerMapping接口的bean,再进行按优先级排序。如果只期望Spring MVC只加载指定的HandlerMapping,可以修改web.xml中的DispatcherServlet的初始化参数,将detectAllHandlerMappings的值设置为false。这样,Spring MVC就只会查找名为“handlerMapping”的bean,并作为当前系统的唯一的HandlerMapping。所以在DispatcherServlet的initHandlerMappings()方法中,优先判断detectAllHandlerMappings的值,再进行下面内容。
如果没有定义HandlerMapping的话,Spring MVC就会按照DispatcherServlet.properties所定义的内容来加载默认的HandlerMapping。
从配置文件中确定了需要初始化的HandlerMapping,而HandlerMapping有很多的实现类,具体的某个实现类是怎么初始化的呢?那么接下来以SimpleUrlHandlerMapping为例,具体看看HandlerMapping的初始化过程。
通过类的结构图,我们知道Spring MVC提供了一个HandlerMapping接口的抽象类AbstractHandlerMapping,而AbstractHandlerMapping同时还实现了Ordered接口并继承了WebApplicationObjectSupport类。可以让HandlerMapping通过设置setOrder()方法提高优先级,并通过覆盖initApplicationContext()方法实现初始化的一些工作。
public final void setApplicationContext(ApplicationContext context) throws BeansException {
if (context == null && !isContextRequired()) {
// Reset internal context state.
this.applicationContext = null;
this.messageSourceAccessor = null;
}
else if (this.applicationContext == null) {
// Initialize with passed-in context.
if (!requiredContextClass().isInstance(context)) {
throw new ApplicationContextException(
"Invalid application context: needs to be of type [" + requiredContextClass().getName() + "]");
}
this.applicationContext = context;
this.messageSourceAccessor = new MessageSourceAccessor(context);
initApplicationContext(context);
}
else {
// Ignore reinitialization if same context passed in.
if (this.applicationContext != context) {
throw new ApplicationContextException(
"Cannot reinitialize with different application context: current one is [" +
this.applicationContext + "], passed-in one is [" + context + "]");
}
}
}
ApplicationObjectSupport首先调用setApplicationContext()方法,其中的initApplicationContext()方法由子类覆盖和实现。
@Override
public void initApplicationContext() throws BeansException {
super.initApplicationContext();
registerHandlers(this.urlMap);
}
在子类SimpleUrlHandlerMapping中的initApplicationContext()方法中,先初始化Spring MVC容器,然后再对Handler进行注册。
protected void initApplicationContext() throws BeansException {
extendInterceptors(this.interceptors);
detectMappedInterceptors(this.mappedInterceptors);
initInterceptors();
}
在SimpleUrlHandlerMapping的父类AbstractHandlerMapping中,detectMappingInterceptors()方法探测ApplicationContext中已经解析过的MappedInterceptor,initInterceptors()方法来初始化拦截器。
protected void initInterceptors() {
if (!this.interceptors.isEmpty()) {
for (int i = 0; i < this.interceptors.size(); i++) {
Object interceptor = this.interceptors.get(i);
if (interceptor == null) {
throw new IllegalArgumentException("Entry number " + i + " in interceptors array is null");
}
if (interceptor instanceof MappedInterceptor) {
mappedInterceptors.add((MappedInterceptor) interceptor);
}
else {
adaptedInterceptors.add(adaptInterceptor(interceptor));
}
}
}
}
调用initInterceptors()方法将SimpleUrlHandlerMapping中定义的interceptors包装成HandlerInterceptor对象保存在adaptedInterceptors数组中。
protected void registerHandlers(Map<String, Object> urlMap) throws BeansException {
if (urlMap.isEmpty()) {
logger.warn("Neither 'urlMap' nor 'mappings' set on SimpleUrlHandlerMapping");
}
else {
for (Map.Entry<String, Object> entry : urlMap.entrySet()) {
String url = entry.getKey();
Object handler = entry.getValue();
// Prepend with slash if not already present.
if (!url.startsWith("/")) {
url = "/" + url;
}
// Remove whitespace from handler bean name.
if (handler instanceof String) {
handler = ((String) handler).trim();
}
registerHandler(url, handler);
}
}
}
再回到initApplicationContext()方法中调用的registerHandlers()方法,这边主要是主要是对urlMap中的key值进行了一些处理,要是没有“/”的就加上"/",去掉空格等处理。这里的urlMap就是在配置文件中SimpleUrlHandlerMapping的通过mappings属性注入的的内容。key是url的某个字段,value是bean的id。
这个方法中的重点是调用了registerHandler(url, handler)这个方法,在这个方法是它的父类AbstractUrlHandlerMapping中的方法。
protected void registerHandler(String urlPath, Object handler) throws BeansException, IllegalStateException {
Assert.notNull(urlPath, "URL path must not be null");
Assert.notNull(handler, "Handler object must not be null");
Object resolvedHandler = handler;
// Eagerly resolve handler if referencing singleton via name.
if (!this.lazyInitHandlers && handler instanceof String) {
String handlerName = (String) handler;
if (getApplicationContext().isSingleton(handlerName)) {
resolvedHandler = getApplicationContext().getBean(handlerName);
}
}
Object mappedHandler = this.handlerMap.get(urlPath);
if (mappedHandler != null) {
if (mappedHandler != resolvedHandler) {
throw new IllegalStateException(
"Cannot map " + getHandlerDescription(handler) + " to URL path [" + urlPath +
"]: There is already " + getHandlerDescription(mappedHandler) + " mapped.");
}
}
else {
if (urlPath.equals("/")) {
if (logger.isInfoEnabled()) {
logger.info("Root mapping to " + getHandlerDescription(handler));
}
setRootHandler(resolvedHandler);
}
else if (urlPath.equals("/*")) {
if (logger.isInfoEnabled()) {
logger.info("Default mapping to " + getHandlerDescription(handler));
}
setDefaultHandler(resolvedHandler);
}
else {
this.handlerMap.put(urlPath, resolvedHandler);
if (logger.isInfoEnabled()) {
logger.info("Mapped URL path [" + urlPath + "] onto " + getHandlerDescription(handler));
}
}
}
}
从这边就可以清楚的看到,这里根据SimpleUrlHandlerMapping中的urlMap中的value值通过getBean()方法得到bean对象(通过id查找)。同时将url的某个字段作为key值,bean作为value重新存入到AbstractUrlHandlerMapping的urlMap属性中去,这样就达到url的某个字段对应到具体的controller了的目的,当遇到有请求访问服务器的时候,就可以根据url找到具体的controller去执行这个请求了。
也就是说,HandlerMapping的初始化过程主要分成两部分,通过initInterceptors()方法将SimpleUrlHandlerMapping中定义的interceptors包装成HandlerInterceptor对象保存在adaptedInterceptors数组中,同时通过registerHandlers()方法将SimpleHandlerMapping中定义的mappings(即URL与Handler的映射)注册到handlerMap集合中。
具体的时序图
————————————————
原文链接:https://blog.csdn.net/qq_38410730/article/details/79507465