RequestMappingHandlerMapping详解
我们先理简单梳理一个关系
关系梳理
- spring ioc 是spring的核心,用来管理spring bean的生命周期
- MVC 是一种使用 MVC(Model View Controller 模型-视图-控制器)设计创建 Web 应用程序的模式
- spring mvc 是spring的一个独立的模块,就像AOP一样
在spring mvc中把web框架和spring ioc融合在一起,是通过ContextLoaderListener监听servlet上下文的创建后来加载父容器完成的,然后通过配置一个servlet对象DispatcherServlet,在初始化DispatcherServlet时来加载具体子容器,详细的可以参考spring ioc & web宿主 这篇文章
关于我们今天要讲的RequestMappingHandlerMapping也是在DispatcherServlet的初始化过程中自动加载的,默认会自动加载所有实现HandlerMapping接口的bean,且我们可以通过serOrder来设置优先级,系统默认会加载RequestMappingHandlerMapping、BeanNameUrlHandlerMapping、SimpleUrlHandlerMapping 并且按照顺序使用
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<>(matchingBeans.values());
// We keep HandlerMappings in sorted order.
AnnotationAwareOrderComparator.sort(this.handlerMappings);
}
}
}
RequestMappingHandlerMapping 加载过程
- RequestMappingHandlerMapping 实现了接口InitializingBean,在bean加载完成后会自动调用afterPropertiesSet方法,在此方法中调用了initHandlerMethods()来实现初始化
- 遍历所有bean,如果bean实现带有注解@Controller或者@RequestMapping 则进一步调用detectHandlerMethods处理,处理逻辑大致就是根据@RequestMapping配置的信息,构建RequestMappingInfo,然后注册到MappingRegistry中
protected void initHandlerMethods() {
String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(obtainApplicationContext(), Object.class) :
obtainApplicationContext().getBeanNamesForType(Object.class));
for (String beanName : beanNames) {
if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
Class<?> beanType = null;
beanType = obtainApplicationContext().getType(beanName);
if (beanType != null && isHandler(beanType)) {
detectHandlerMethods(beanName);
}
}
}
handlerMethodsInitialized(getHandlerMethods());
}
protected void detectHandlerMethods(final Object handler) {
Class<?> handlerType = (handler instanceof String ?
obtainApplicationContext().getType((String) handler) : handler.getClass());
if (handlerType != null) {
final Class<?> userType = ClassUtils.getUserClass(handlerType);
Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
(MethodIntrospector.MetadataLookup<T>) method -> {
try {
return getMappingForMethod(method, userType);
}
catch (Throwable ex) {
throw new IllegalStateException("Invalid mapping on handler class [" +
userType.getName() + "]: " + method, ex);
}
});
methods.forEach((method, mapping) -> {
Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
registerHandlerMethod(handler, invocableMethod, mapping);
});
}
}
RequestMappingHandlerMapping 解析过程
- 在DispatcherServlet中,根据请求对象调用getHander方法获取HandlerExecutionChain对象
- 在getHander方法中也是遍历上面默认加载的三个HandlerMapping,当然第一个就是RequestMappingHandlerMapping对象,调用其getHandler方法,根据请求path,找到一个最为匹配的HandlerMethod来处理请求
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
if (this.handlerMappings != null) {
for (HandlerMapping hm : this.handlerMappings) {
if (logger.isTraceEnabled()) {
logger.trace(
"Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'");
}
HandlerExecutionChain handler = hm.getHandler(request);
if (handler != null) {
return handler;
}
}
}
return null;
}
- 根据请求路径获取HandlerInterceptor,然后和上面获得的HandlerMethod一起构成HandlerExecutionChain返回给DispatcherServlet
DispatcherServlet得到HandlerExecutionChain也就获得了处理此次请求所需的Handler【即我们熟悉的Controller和对应的Action】,后续将会选择合适HandlerAdapter来执行对应的Handler,获取返回值,再根据返回值类型,进一步觉决定用什么方式展示给用户
链接:https://www.jianshu.com/p/40eff6135311
RequestMappingHandlerMapping详解的更多相关文章
- RequestMappingHandlerMapping 详解
我们先理简单梳理一个关系 关系梳理 spring ioc 是spring的核心,用来管理spring bean的生命周期 MVC 是一种使用 MVC(Model View Controller 模型- ...
- spring-mvc注解(mvc:annotation-driver,JSON,配置详解)
一.DefaultAnnotationHandlerMapping 和 AnnotationMethodHandlerAdapter 的使用已经过时! spring 3.1 开始我们应该用 Reque ...
- Spring MVC 学习总结(二)——控制器定义与@RequestMapping详解
一.控制器定义 控制器提供访问应用程序的行为,通常通过服务接口定义或注解定义两种方法实现. 控制器解析用户的请求并将其转换为一个模型.在Spring MVC中一个控制器可以包含多个Action(动作. ...
- SpringMVC异常处理机制详解[附带源码分析]
目录 前言 重要接口和类介绍 HandlerExceptionResolver接口 AbstractHandlerExceptionResolver抽象类 AbstractHandlerMethodE ...
- HandlerMapping 详解
HandlerMapping 详解 1. 导言 万丈高楼平地起,SpringMVC的辉煌离不开每个组件的相互协作,上一章详细阐述了SpringMVC整个体系结构及实现原理,知道HandlerMappi ...
- 详解SpringMVC请求的时候是如何找到正确的Controller
详解SpringMVC请求的时候是如何找到正确的Controller[附带源码分析] 目录 前言 源码分析 重要接口介绍 SpringMVC初始化的时候做了什么 HandlerExecutionCha ...
- SpringMVC 框架系列之组件概述与配置详解
在上一篇文章 SpringMVC 框架系列之初识与入门实例 的实例中,我们已经知道,SpringMVC 框架是一个 web 层的框架,本篇文章就详细解释一下 SpringMVC 框架具体文件的配置以及 ...
- SpringMVC【开发Controller】详解
前言 本文主要是讲解在Controller中的开发,主要的知识点有如下: 编码过滤器 使用注解开发 注解@RequestMapping详解 业务方法接收参数 字符串转日期 重定向和转发 返回JSON ...
- 转载 Spring、Spring MVC、MyBatis整合文件配置详解
Spring.Spring MVC.MyBatis整合文件配置详解 使用SSM框架做了几个小项目了,感觉还不错是时候总结一下了.先总结一下SSM整合的文件配置.其实具体的用法最好还是看官方文档. ...
随机推荐
- HDU 6121 Build a tree(k叉树的子树大小相异)
http://acm.hdu.edu.cn/showproblem.php?pid=6121 题目大意: 给你一颗 n 个节点的完全 k 叉树,问你这棵树中所有子树结点个数的总异或值. 分析: 我们很 ...
- joke python
w # -*- coding: utf-8 -*- import pycurl import re import cStringIO from pypinyin import lazy_pinyin ...
- spring-cloud zuul网关
API Gateway 是随着微服务(Microservice)这个概念一起兴起的一种架构模式,它用于解决微服务过于分散,没有一个统一的出入口进行流量管理的问题. 使用 Zuul 实现 API Gat ...
- Python3.5自带venv创建虚拟环境
为每个程序单独创建虚拟环境可以保证程序只能访问虚拟环境中的包,保持全局解释器的干净整洁,使其只作为创建(更多)虚拟环境的源. windows下创建虚拟环境 Python3.5自带venv,只需执行py ...
- cmath模块——复数域数学函数模块
cmath——复数域数学函数模块 转自:https://blog.csdn.net/zhtysw/article/category/7511293 该模块属于内置模块,随时可以调用.它提供了数学函数在 ...
- 用BP人工神经网络识别手写数字
http://wenku.baidu.com/link?url=HQ-5tZCXBQ3uwPZQECHkMCtursKIpglboBHq416N-q2WZupkNNH3Gv4vtEHyPULezDb5 ...
- GitLab 安装,配置及维护
参考: GitLab 官方文档 docker-gitlab,通过 docker-compose 快速安装 GitLab rake,是 Rails 的工具,类似 ruby 中常用的的 make.通过 R ...
- Altium Designer chapter2总结
原理图开发环境这节中需要注意的如下: (1)电路图首先项设定中需注意的地方: 1.General:中经常用到的自动生成交叉节点.放置元件时自动增加选项.复合封装元件的字母数字后缀选项.默认电源对象名称 ...
- Item-Based Collaborative Recommender System
与User-Based Collaborative Recommender System认为‘类似的用户会对同一个item给出类似的打分’不同,Item-Based Collaborative Rec ...
- python3.7.0 安装与配置
python 3.7.0 X64下载地址: https://www.python.org/ftp/python/3.7.0/python-3.7.0-amd64.exe 更多版本下载请移步到:http ...