原文转自:https://blog.csdn.net/nuomizhende45/article/details/85715148
请求流程原理:
- 第一步:发起请求到前端控制器(DispatcherServlet)
- 第二步:前端控制器请求HandlerMapping查找 Handler (可以根据xml配置、注解进行查找)
- 第三步:处理器映射器HandlerMapping向前端控制器返回Handler,HandlerMapping会把请求映射为HandlerExecutionChain对象(包含一个Handler处理器(页面控制器)对象,多个HandlerInterceptor拦截器对象),通过这种策略模式,很容易添加新的映射策略
- 第四步:前端控制器调用处理器适配器去执行Handler
- 第五步:处理器适配器HandlerAdapter将会根据适配的结果去执行Handler
- 第六步:Handler执行完成给适配器返回ModelAndView
- 第七步:处理器适配器向前端控制器返回ModelAndView (ModelAndView是springmvc框架的一个底层对象,包括 Model和view)
- 第八步:前端控制器请求视图解析器去进行视图解析 (根据逻辑视图名解析成真正的视图(jsp)),通过这种策略很容易更换其他视图技术,只需要更改视图解析器即可
- 第九步:视图解析器向前端控制器返回View
- 第十步:前端控制器进行视图渲染 (视图渲染将模型数据(在ModelAndView对象中)填充到request域)
- 第十一步:前端控制器向用户响应结果
请求流程图:
一、发起请求到前端控制器DispatcherServlet,分析DispatcherServlet类的结构
这里我们发现了这个DispatcherServlet通过继承FrameWorkServlet、HttpServletBean从而间接的继承了HttpServlet,所以说这个DispatcherServlet也是一个Servlet,它也能通过Servlet的API来响应请求,从而成为一个前端控制器。Web容器会调用Servlet的doGet()以及doPost()等方法,这里FrameworkServlet重写了HttpServlet的这两个方法,里面都调用了processRequest这个方法
继续跟进,经过了一些简单的处理后发现最终还是调用了doService方法
继续跟进这个doService方法,发现它是一个等待子类实现的抽象方法,DispatcherServlet是它的子类并且实现了该方法,所以最终请求时通过FrameworkServlet的简单处理之后调用了DispatcherServlet的doService方法。
至此我们已经清楚了为什么DispatcherServlet为前端控制器了
二、分析前端控制器DispatcherServlet的启动和初始化的过程
通过前面分析已经知道了DispatcherServlet这个前端控制器是一个Servlet了,所以生命周期和普通的Servlet是差不多的,在一个Servlet初始化的时候都会调用该Servlet的init()方法。下面这个是DispatcherSerlvet父类HttpServletBean中的init方法。
我们发现这里会调用initServletBean()方法进行具体的初始化,而该类这个方法的具体实现这是其子类FrameworkServlet。主要逻辑就是初始化上下文。
- protected final void initServletBean() throws ServletException {
- this.getServletContext().log("Initializing Spring " + this.getClass().getSimpleName() + " \'" + this.getServletName() + "\'");
- if(this.logger.isInfoEnabled()) {
- this.logger.info("Initializing Servlet \'" + this.getServletName() + "\'");
- }
- long startTime = System.currentTimeMillis();
- try {
- /**
- 这里初始化上下文
- **/
- this.webApplicationContext = this.initWebApplicationContext();
- this.initFrameworkServlet();
- } catch (RuntimeException | ServletException var4) {
- this.logger.error("Context initialization failed", var4);
- throw var4;
- }
- if(this.logger.isDebugEnabled()) {
- String value = this.enableLoggingRequestDetails?"shown which may lead to unsafe logging of potentially sensitive data":"masked to prevent unsafe logging of potentially sensitive data";
- this.logger.debug("enableLoggingRequestDetails=\'" + this.enableLoggingRequestDetails + "\': request parameters and headers will be " + value);
- }
- if(this.logger.isInfoEnabled()) {
- this.logger.info("Completed initialization in " + (System.currentTimeMillis() - startTime) + " ms");
- }
- }
继续跟进这个onRefresh方法,发现是一个模板方法,其具体实现子类则是DispatcherServlet。
跳转到DispatcherServlet中查看该方法,发现里面又调用了initStrategies这个方法
这时我们就大致了解了,这个DispatcherServlet初始化的过程了,首先DispatcherServlet持有着一个以自己的Servlet名字命名的Ioc容器,也就是我们看到的WebApplicationContext对象,这个Ioc容器建立起来后,与Web容器相关的各种配置加载也都完成了。并且这个初始化的入口就是由最初的HttpServletBean的init方法触发的,因为这个HttpServletBean是HttpServlet的子类,接下来HttpServletBean的子类FrameworkServlet对Ioc容器进行了初始化操作,并且利用onRefresh方法回调了DispatcherServlet中的initStrategies方法,在这个方法里启动了整个SpringMVC框架,我们继续往下面跟进看看。
- //该属性默认为true
- private boolean detectAllHandlerMappings = true;
- private void initHandlerMappings(ApplicationContext context) {
- this.handlerMappings = null;
- //这里面的逻辑是从导入所有的HandlerMappingBean,这些Bean有可能存在与双亲容器中,也可能在DispathcerServlet持有的容器的,这里detectAllHandlerMappings默认为true,默认从所有容器中导入
- if(this.detectAllHandlerMappings) {
- Map hm = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
- if(!hm.isEmpty()) {
- this.handlerMappings = new ArrayList(hm.values());
- AnnotationAwareOrderComparator.sort(this.handlerMappings);
- }
- } else {
- //否则通过直接通过名字从当前的IOC容器中通过getBean方法获取handlerMapping
- try {
- HandlerMapping hm1 = (HandlerMapping)context.getBean("handlerMapping", HandlerMapping.class);
- this.handlerMappings = Collections.singletonList(hm1);
- } catch (NoSuchBeanDefinitionException var3) {
- ;
- }
- }
- //如果还是没有找到hadlerMapping就需要设定默认的handlerMappings了
- if(this.handlerMappings == null) {
- this.handlerMappings = this.getDefaultStrategies(context, HandlerMapping.class);
- if(this.logger.isTraceEnabled()) {
- this.logger.trace("No HandlerMappings declared for servlet \'" + this.getServletName() + "\': using default strategies from DispatcherServlet.properties");
- }
- }
- }
下面是用debugger看看它究竟获取了那些handlerMapping,如下:7个handlerMapping
除了这个初始化handlerMapping的initHandlerMapping方法,当然还初始化了很多东西,如支持国际化的LocalResolver以及视图生成的ViewResolver等的初始化过程,其余的有兴趣自己跟着看一下,这里就不细跟了。到这里我们就知道了整个DispatcherServlet的初始化的大体流程。接下来继续了解以下MVC是如何处理我们HTTP请求并映射到对应的handler处理的,也就是对应着最上面的二、三、四、五步骤。
三、HTTP请求是如何与对应Handler的对应method映射的
从上面的分析已经知道了当初始化完成的时候context中所有的handlerMapping都被加载了,并且它们都存放在hadlerMappings这么一个List中并且被排序了。我们看看HandlerMapping的设计及类的结构关系如下:
这里可以看到顶层的父接口就是HandlerMapping,进入这个类发现这个顶层接口定义了一些常量以及一个getHandler方法,并且通过该方法会返回HandlerExecutionChain这么一个对象。
跟进这个HandlerExecutionChain这个类看看,这个类中有这么Interceptor链和一个handler这个两个关键的成员。说白了这个handler就是HTTP请求对应的那个Controller,并且这个Interceptor链也就是我们配置的各种拦截器,多个拦截器组成了拦截器链,通过拦截器链对我们handler进行一系列的增强。当然这个HandlerExecutionChain类还提供了一些维护这个拦截器链的API
- public class HandlerExecutionChain {
- private static final Log logger = LogFactory.getLog(HandlerExecutionChain.class);
- private final Object handler;
- @Nullable
- private HandlerInterceptor[] interceptors;
- @Nullable
- private List<HandlerInterceptor> interceptorList;
- private int interceptorIndex;
- public HandlerExecutionChain(Object handler) {
- this(handler, (HandlerInterceptor[])null);
- }
- public HandlerExecutionChain(Object handler, @Nullable HandlerInterceptor... interceptors) {
- this.interceptorIndex = -1;
- if(handler instanceof HandlerExecutionChain) {
- HandlerExecutionChain originalChain = (HandlerExecutionChain)handler;
- this.handler = originalChain.getHandler();
- this.interceptorList = new ArrayList();
- CollectionUtils.mergeArrayIntoCollection(originalChain.getInterceptors(), this.interceptorList);
- CollectionUtils.mergeArrayIntoCollection(interceptors, this.interceptorList);
- } else {
- this.handler = handler;
- this.interceptors = interceptors;
- }
- }
- public Object getHandler() {
- return this.handler;
- }
- public void addInterceptor(HandlerInterceptor interceptor) {
- this.initInterceptorList().add(interceptor);
- }
- public void addInterceptors(HandlerInterceptor... interceptors) {
- if(!ObjectUtils.isEmpty(interceptors)) {
- CollectionUtils.mergeArrayIntoCollection(interceptors, this.initInterceptorList());
- }
- }
- private List<HandlerInterceptor> initInterceptorList() {
- if(this.interceptorList == null) {
- this.interceptorList = new ArrayList();
- if(this.interceptors != null) {
- CollectionUtils.mergeArrayIntoCollection(this.interceptors, this.interceptorList);
- }
- }
- this.interceptors = null;
- return this.interceptorList;
- }
- @Nullable
- public HandlerInterceptor[] getInterceptors() {
- if(this.interceptors == null && this.interceptorList != null) {
- this.interceptors = (HandlerInterceptor[])this.interceptorList.toArray(new HandlerInterceptor[0]);
- }
- return this.interceptors;
- }
- boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
- HandlerInterceptor[] interceptors = this.getInterceptors();
- if(!ObjectUtils.isEmpty(interceptors)) {
- for(int i = 0; i < interceptors.length; this.interceptorIndex = i++) {
- HandlerInterceptor interceptor = interceptors[i];
- if(!interceptor.preHandle(request, response, this.handler)) {
- this.triggerAfterCompletion(request, response, (Exception)null);
- return false;
- }
- }
- }
- return true;
- }
- void applyPostHandle(HttpServletRequest request, HttpServletResponse response, @Nullable ModelAndView mv) throws Exception {
- HandlerInterceptor[] interceptors = this.getInterceptors();
- if(!ObjectUtils.isEmpty(interceptors)) {
- for(int i = interceptors.length - 1; i >= 0; --i) {
- HandlerInterceptor interceptor = interceptors[i];
- interceptor.postHandle(request, response, this.handler, mv);
- }
- }
- }
- void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, @Nullable Exception ex) throws Exception {
- HandlerInterceptor[] interceptors = this.getInterceptors();
- if(!ObjectUtils.isEmpty(interceptors)) {
- for(int i = this.interceptorIndex; i >= 0; --i) {
- HandlerInterceptor interceptor = interceptors[i];
- try {
- interceptor.afterCompletion(request, response, this.handler, ex);
- } catch (Throwable var8) {
- logger.error("HandlerInterceptor.afterCompletion threw exception", var8);
- }
- }
- }
- }
- void applyAfterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response) {
- HandlerInterceptor[] interceptors = this.getInterceptors();
- if(!ObjectUtils.isEmpty(interceptors)) {
- for(int i = interceptors.length - 1; i >= 0; --i) {
- if(interceptors[i] instanceof AsyncHandlerInterceptor) {
- try {
- AsyncHandlerInterceptor ex = (AsyncHandlerInterceptor)interceptors[i];
- ex.afterConcurrentHandlingStarted(request, response, this.handler);
- } catch (Throwable var6) {
- logger.error("Interceptor [" + interceptors[i] + "] failed in afterConcurrentHandlingStarted", var6);
- }
- }
- }
- }
- }
- public String toString() {
- Object handler = this.getHandler();
- StringBuilder sb = new StringBuilder();
- sb.append("HandlerExecutionChain with [").append(handler).append("] and ");
- if(this.interceptorList != null) {
- sb.append(this.interceptorList.size());
- } else if(this.interceptors != null) {
- sb.append(this.interceptors.length);
- } else {
- sb.append(0);
- }
- return sb.append(" interceptors").toString();
- }
- }
大致了解了Handler与HandlerExecutionChain后,就可以开始具体分析SpringMVC对HTTP请求处理的原理了,这里以我们最常用的RequestMappingHandlerMapping为例子,首先看看它的类继承体系
这里主要关注的是RequestMappingInfoHandlerMapping、AbstractHandlerMethodMapping。从这张Diagrams图可以发现,这个AbstractHandlerMethodMapping实现了InitializingBean接口并且实现了afterPropertiesSet方法。
并且整个初始化工作由AbstractHandlerMethodMapping的initHandlerMethods方法主导的。为什么这么说呢,我们都知道SpringBean在创建bean的过程是先经过了bean的实例化、bean的属性填充、bean的初始化等步骤。
那么在SpringBean初始化的时候会调用invokeInitMethods方法它会去判断该bean是否为InitializingBean的实例,是的话就去调用它的afterPropertiesSet方法
到这里终于清楚了为什么说整个初始化的工作是由AbstractHandlerMethodMapping的initHandlerMethods主导了,原因就是在这个类中Spring回调方法afterPropertiesSet里面又调用了initHandlerMethods方法。
接下来主要分析以下这个initHandlerMethods方法究竟干了什么,大体逻辑就是先获取应用中所有Object的bean的名字,然后遍历它循环获取这个beanName对应的beanType,判断这个bean是不是一个handler
- protected void initHandlerMethods() {
- if(this.logger.isDebugEnabled()) {
- this.logger.debug("Looking for request mappings in application context: " + this.getApplicationContext());
- }
- //这里是获取应用中所有Object的bean的名字
- String[] beanNames = this.detectHandlerMethodsInAncestorContexts?BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.obtainApplicationContext(), Object.class):this.obtainApplicationContext().getBeanNamesForType(Object.class);
- String[] var2 = beanNames;
- int var3 = beanNames.length;
- //遍历这个含有应用中所有beanName的字符串数组,并得到这个beanName对应的bean的类型
- for(int var4 = 0; var4 < var3; ++var4) {
- String beanName = var2[var4];
- if(!beanName.startsWith("scopedTarget.")) {
- Class beanType = null;
- try {
- //根据这个beanName对应的beanType的类型
- beanType = this.obtainApplicationContext().getType(beanName);
- } catch (Throwable var8) {
- if(this.logger.isDebugEnabled()) {
- this.logger.debug("Could not resolve target class for bean with name \'" + beanName + "\'", var8);
- }
- }
- //判断这个根据这个bean的类型判断是不是一个handler
- if(beanType != null && this.isHandler(beanType)) {
- this.detectHandlerMethods(beanName);
- }
- }
- }
- this.handlerMethodsInitialized(this.getHandlerMethods());
- }
并且从代码中我们可以知道判断一个Bean是不是一个Handler的逻辑就是判断这个Bean是否含有Controller注解或RequestMapping注解
若这个Bean是一个Handler那么就进入detectHandlerMethods方法处理,去检测发现对应的HandlerMethod。继续跟进这个方法看看。这个方法的大体逻辑是获取这个handler中所有由requestMappinng的方法,然后循环去注册该方法与对应requestMapping信息到一个名为registry的一个HashMap中去,具体逻辑继续往下看。
- protected void detectHandlerMethods(Object handler) {
- Class handlerType = handler instanceof String?this.obtainApplicationContext().getType((String)handler):handler.getClass();
- if(handlerType != null) {
- Class userType = ClassUtils.getUserClass(handlerType);
- //获取这个handler中有requestMapping的方法
- //这个methods的Map结构为key是一个Method对象,value是一个RequestMappingInfo对象
- //这个版本的代码是5.0.4的,这里用到了lambda表达,这里可以理解成匿名类
- Map methods = MethodIntrospector.selectMethods(userType, (method) -> {
- try {
- return this.getMappingForMethod(method, userType);
- } catch (Throwable var4) {
- throw new IllegalStateException("Invalid mapping on handler class [" + userType.getName() + "]: " + method, var4);
- }
- });
- if(this.logger.isDebugEnabled()) {
- this.logger.debug(methods.size() + " request handler methods found on " + userType + ": " + methods);
- }
- //循环去注册Method与RequestMappingInfo的关系
- methods.forEach((method, mapping) -> {
- Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
- this.registerHandlerMethod(handler, invocableMethod, mapping);
- });
- }
- }
首先看看这个selectMethods方法到底做了什么,从字面意思理解是按照规则来选取给定的类里面中方法。具体逻辑细化可以分为两步.
第一步:若这个targetType不是一个代理类,就获得它本身的类以及它的接口放入handlerTypes这么一个Set中去。
第二步:遍历这个handlerTypes,找到用户自己定义的方法并过滤出有requestMapping的方法,并将之塞入一个methodMap中
- public static <T> Map<Method, T> selectMethods(Class<?> targetType, MethodIntrospector.MetadataLookup<T> metadataLookup) {
- LinkedHashMap methodMap = new LinkedHashMap();
- LinkedHashSet handlerTypes = new LinkedHashSet();
- Class specificHandlerType = null;
- //若这个targetType不是一个代理类,就获得它本身的类以及它的接口
- if(!Proxy.isProxyClass(targetType)) {
- specificHandlerType = ClassUtils.getUserClass(targetType);
- handlerTypes.add(specificHandlerType);
- }
- handlerTypes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetType));
- Iterator var5 = handlerTypes.iterator();
- //遍历
- while(var5.hasNext()) {
- Class currentHandlerType = (Class)var5.next();
- Class targetClass = specificHandlerType != null?specificHandlerType:currentHandlerType;
- //找到用户自己定义的方法并过滤出有requestMapping的方法,并将之塞入一个methodMap中
- ReflectionUtils.doWithMethods(currentHandlerType, (method) -> {
- Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
- Object result = metadataLookup.inspect(specificMethod);
- if(result != null) {
- Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
- if(bridgedMethod == specificMethod || metadataLookup.inspect(bridgedMethod) == null) {
- methodMap.put(specificMethod, result);
- }
- }
- }, ReflectionUtils.USER_DECLARED_METHODS);
- }
- return methodMap;
- }
下面继续跟进这个ReflectUtilsl.doWithMethods方法看看究竟是何方神圣。
先来了解以下它的方法入参:第一个是Class、第二个是MethodCallback、第三个是MethodFilter。第一个不用解释了,第二个从字面意思就能看出来就是一个方法回调,第三个也好理解是一个方法过滤器;具体后面再说。
大致清楚它的参数后再来看看这个方法的内部逻辑,可以看到逻辑也比较简单:
1、首先获取这个Class中所有定义的方法并且将之存入一个methods的Method数组中
2、遍历这个methods数组中的method如果这个mf方法拦截器为空或者这个method与方法拦截器mf的匹配规则对应,就回调mc.doWith方法。
3、后面我们还发现对这个类的父类和接口都有一个递归调用
- public static void doWithMethods(Class<?> clazz, ReflectionUtils.MethodCallback mc, @Nullable ReflectionUtils.MethodFilter mf) {
- //首先获取这个Class中所有定义的方法并且将之存入一个methods的Method数组中
- Method[] methods = getDeclaredMethods(clazz);
- Method[] var4 = methods;
- int var5 = methods.length;
- int var6;
- for(var6 = 0; var6 < var5; ++var6) {
- Method superIfc = var4[var6];
- //遍历这个methods数组中的method
- //如果这个mf方法拦截器为空或者这个method与方法拦截器mf的匹配规则对应,就回调mc.doWith方法。
- if(mf == null || mf.matches(superIfc)) {
- try {
- //调用回调方法
- mc.doWith(superIfc);
- } catch (IllegalAccessException var9) {
- throw new IllegalStateException("Not allowed to access method \'" + superIfc.getName() + "\': " + var9);
- }
- }
- }
- if(clazz.getSuperclass() != null) {
- doWithMethods(clazz.getSuperclass(), mc, mf);
- } else if(clazz.isInterface()) {
- Class[] var10 = clazz.getInterfaces();
- var5 = var10.length;
- for(var6 = 0; var6 < var5; ++var6) {
- Class var11 = var10[var6];
- doWithMethods(var11, mc, mf);
- }
- }
- }
了解这个方法的逻辑之后,再回过头来看看selectMethod方法中的ReflectUtilsl.doWithMethods就很清楚了。
这个mc.doWith就对应这一段逻辑,可以看到这段逻辑里面有一个metadataLookup.inspect方法,这个方法的逻辑就是selectMethods传入的第二个入参的。就是调用了RequestMappingHandlerMapping的getMappingForMethod方法
而这个getMappingForMethod干的事情就是找到这个方法上的RequestMapping,如果这个方法上的requestMapping信息不为空的话就去照这个handler类上面的requestMapping信息然后将之合并。
然后这个mf方法拦截器就是这个RelectionUtils.USER_DECLARED_METHODS;顾名思义就是用户自己定义的方法,而非继承与Object类的方法什么的
所以这下detectHandlerMethods里面上半部分在干什么就已经知道了:无非就是获取这个handler类里面用户自定义的方法中有requestMapping注解信息的方法,并将该方法作为key,requestMapping注解信息作为value存入一个名为methods的Map中去
这里不得不提到这个RequestMappingInfo这个类,这个类就是封装了requestMapping注解信息的这么一个类,有兴趣的可以自己去看看它的内部定义,这里就不详解了。
接下来这个方法中就只剩下了这么一小段逻辑了,看名字就知道应该是遍历这个methods注册handlerMethod到某个地方去。
继续跟进这个方法看看,里面并没有做什么而是调用了另外一个方法,继续跟进。
终于找到了最终的实现,首先加了一把锁,考虑的两个requestMapping并发注册的问题;然后根据这个handler与method获取了一个HandlerMethod对象,这个对象包含了handler与method的信息;接着确保同一个requestMapping唯一映射一个method,因为不可能说一个url路径 /aaa/bbb 又对应methodA 又对应methodB是不允许的’;最终注册这个requestMappingInfo与对应handlerMethod的关系。(这里有意思的事情是发现有这么一个log的info语句 “Mapped xxx onto xxxx” 是不是在SpringBoot项目或者SpringMVC项目启动的时候控制台上见过,没错就是这里的)
- public void register(T mapping, Object handler, Method method) {
- this.readWriteLock.writeLock().lock();
- try {
- //根据这个handler与method获取了一个HandlerMethod对象,这个对象包含了handler与method的信息
- HandlerMethod handlerMethod = AbstractHandlerMethodMapping.this.createHandlerMethod(handler, method);
- //确保同一个requestMapping唯一映射一个method
- //因为不可能说一个url路径 /aaa/bbb 又对应methodA 又对应methodB是不允许的
- this.assertUniqueMethodMapping(handlerMethod, mapping);
- if(AbstractHandlerMethodMapping.this.logger.isInfoEnabled()) {
- AbstractHandlerMethodMapping.this.logger.info("Mapped \"" + mapping + "\" onto " + handlerMethod);
- }
- //后面都差不多是注册requestMapping与HandlerMethodInfo的关系
- this.mappingLookup.put(mapping, handlerMethod);
- List directUrls = this.getDirectUrls(mapping);
- Iterator name = directUrls.iterator();
- while(name.hasNext()) {
- String corsConfig = (String)name.next();
- this.urlLookup.add(corsConfig, mapping);
- }
- String name1 = null;
- if(AbstractHandlerMethodMapping.this.getNamingStrategy() != null) {
- name1 = AbstractHandlerMethodMapping.this.getNamingStrategy().getName(handlerMethod, mapping);
- this.addMappingName(name1, handlerMethod);
- }
- CorsConfiguration corsConfig1 = AbstractHandlerMethodMapping.this.initCorsConfiguration(handler, method, mapping);
- if(corsConfig1 != null) {
- this.corsLookup.put(handlerMethod, corsConfig1);
- }
- this.registry.put(mapping, new AbstractHandlerMethodMapping.MappingRegistration(mapping, handlerMethod, directUrls, name1));
- } finally {
- this.readWriteLock.writeLock().unlock();
- }
- }
至此这个 detectHandlerMethods 方法的逻辑全都清楚了,前面先找寻出又requestMapping信息的method,接着就是将这个handler里面的RequestMappingInfo与一个HandlerMethod建立映射关系。
所以建立映射关系这一步已经全都清楚了,最后贴一个启动的控制台语句,果然对应的上非常 的有成就感啊。
小结:
说白了我们常用的@RequestMapping映射处理的初始化是由SpringIOC的这么一个回调接口InitializingBean来主导的,由于AbstractHandlerMethodMapping这个父类实现了InitializingBean,所以SpringIOC容器会回调父类的这么一个afterPropertiesSet方法,最后间接的调用了initHandlerMethods这个方法。在initHandlerMethods这个方法里面就是得到容器中所有的beanName,遍历这个beanName得到它的beanType,再看这个beanType是不是由@Controller或者@RequestMapping这个注解判断它是否是一个Handler,若是就去获取这个handler中所有含有requestMapping的方法,并放入一个key为Method并且value为RequestMappingInfo这么Map中去,接着遍历这个map注册ReuquestMappingInfo与HandlerMethod这么一个映射关系。这个HandlerMethod方法其实就是包含着handler与method的这么一个类。
四、SpingMVC处理Http请求原理
当一个http请求过来了首先经过的是DispatcherServlet这么一个前端控制器并调用了这个前端控制器的doService方法。这个方法最终我们发现它调用了doDispatcher这么一个方法。这就是SpringMVC处理http请求的入口了。
- protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
- if(this.logger.isDebugEnabled()) {
- String attributesSnapshot = WebAsyncUtils.getAsyncManager(request).hasConcurrentResult()?" resumed":"";
- this.logger.debug("DispatcherServlet with name \'" + this.getServletName() + "\'" + attributesSnapshot + " processing " + request.getMethod() + " request for [" + getRequestUri(request) + "]");
- }
- HashMap attributesSnapshot1 = null;
- if(WebUtils.isIncludeRequest(request)) {
- attributesSnapshot1 = new HashMap();
- Enumeration inputFlashMap = request.getAttributeNames();
- label112:
- while(true) {
- String attrName;
- do {
- if(!inputFlashMap.hasMoreElements()) {
- break label112;
- }
- attrName = (String)inputFlashMap.nextElement();
- } while(!this.cleanupAfterInclude && !attrName.startsWith("org.springframework.web.servlet"));
- attributesSnapshot1.put(attrName, request.getAttribute(attrName));
- }
- }
- request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.getWebApplicationContext());
- request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
- request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);
- request.setAttribute(THEME_SOURCE_ATTRIBUTE, this.getThemeSource());
- if(this.flashMapManager != null) {
- FlashMap inputFlashMap1 = this.flashMapManager.retrieveAndUpdate(request, response);
- if(inputFlashMap1 != null) {
- request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap1));
- }
- request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
- request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);
- }
- try {
- this.doDispatch(request, response);
- } finally {
- if(!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted() && attributesSnapshot1 != null) {
- this.restoreAttributesAfterInclude(request, attributesSnapshot1);
- }
- }
- }
这个方法里面我们发现定义了一个ModelAndView将要返回的视图与数据,并且首先检测这个请求是不是一个上传的请求,然后根据这个请求获取对应的Handler,如果Handler不为空的话就根据这个handler获取对应的HandlerAdapter。接着调用拦截器链的所有前置拦截的这么一个方法,接着调用adapter的真正的处理方法处理请求,最后调用拦截器链中的所有后置拦截方法。
- protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
- HttpServletRequest processedRequest = request;
- HandlerExecutionChain mappedHandler = null;
- boolean multipartRequestParsed = false;
- WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
- try {
- try {
- //定义一个空的ModelAndView
- ModelAndView err = null;
- Object dispatchException = null;
- try {
- //检查是否是上传请求
- processedRequest = this.checkMultipart(request);
- multipartRequestParsed = processedRequest != request;
- //获取handler
- mappedHandler = this.getHandler(processedRequest);
- if(mappedHandler == null) {
- this.noHandlerFound(processedRequest, response);
- return;
- }
- //根据handler获取handlerAdapter
- HandlerAdapter err1 = this.getHandlerAdapter(mappedHandler.getHandler());
- String method = request.getMethod();
- boolean isGet = "GET".equals(method);
- if(isGet || "HEAD".equals(method)) {
- long lastModified = err1.getLastModified(request, mappedHandler.getHandler());
- if(this.logger.isDebugEnabled()) {
- this.logger.debug("Last-Modified value for [" + getRequestUri(request) + "] is: " + lastModified);
- }
- if((new ServletWebRequest(request, response)).checkNotModified(lastModified) && isGet) {
- return;
- }
- }
- //前置拦截
- if(!mappedHandler.applyPreHandle(processedRequest, response)) {
- return;
- }
- //真正处理
- err = err1.handle(processedRequest, response, mappedHandler.getHandler());
- if(asyncManager.isConcurrentHandlingStarted()) {
- return;
- }
- this.applyDefaultViewName(processedRequest, err);
- //后置拦截
- mappedHandler.applyPostHandle(processedRequest, response, err);
- }
- //后面一些catch finally语句省略。。。。。
继续跟进这个getHandler方法看看具体是怎么实现的,发现就是循环遍历最开始初始化DispatcherServlet的时候初始化的那7个handlerMapping,去调用这些handlerMapping的getHandler方法;这里我们主要看这个RequestMappingHandlerMapping。
跟进发现是调用了RequestMappingHandlerMapping的父类AbstractHandlerMapping中的getHandler方法,并且这个方法又是去调用了getHandlerInternal来获取Handler的。
继续跟进这个getHandlerInternal方法,首先它根据这个request获取它的URI,接着通过uri获取对应的HandlerMethod对象最终返回了。
- protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
- String lookupPath = this.getUrlPathHelper().getLookupPathForRequest(request);
- if(this.logger.isDebugEnabled()) {
- this.logger.debug("Looking up handler method for path " + lookupPath);
- }
- this.mappingRegistry.acquireReadLock();
- HandlerMethod var4;
- try {
- HandlerMethod handlerMethod = this.lookupHandlerMethod(lookupPath, request);
- if(this.logger.isDebugEnabled()) {
- if(handlerMethod != null) {
- this.logger.debug("Returning handler method [" + handlerMethod + "]");
- } else {
- this.logger.debug("Did not find handler method for [" + lookupPath + "]");
- }
- }
- var4 = handlerMethod != null?handlerMethod.createWithResolvedBean():null;
- } finally {
- this.mappingRegistry.releaseReadLock();
- }
- return var4;
- }
跟进这个getLookupPathForRequest发现又调用了getPathWithinServletMapping方法。
这里我们就知道了这个lookupPath得到的就是这个请求的URI,拿到了这个URI接着就去调用lookupHandlerMethod方法了。
这里lookupHandlerMethod方法顾名思义就是通过这个URI根据请求的URI去寻找对应的HandlerMethod。
- protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
- ArrayList matches = new ArrayList();
- //通过这个uri去Map中查询与那个HandlerMethod映射
- List directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);
- if(directPathMatches != null) {
- this.addMatchingMappings(directPathMatches, matches, request);
- }
- if(matches.isEmpty()) {
- this.addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, request);
- }
- //若查询出这个uri有对应的映射关系
- if(!matches.isEmpty()) {
- AbstractHandlerMethodMapping.MatchComparator comparator = new AbstractHandlerMethodMapping.MatchComparator(this.getMappingComparator(request));
- //对映射关系排序
- matches.sort(comparator);
- if(this.logger.isTraceEnabled()) {
- this.logger.trace("Found " + matches.size() + " matching mapping(s) for [" + lookupPath + "] : " + matches);
- }
- //获取排序后第一个HandlerMethod
- AbstractHandlerMethodMapping.Match bestMatch = (AbstractHandlerMethodMapping.Match)matches.get(0);
- if(matches.size() > 1) {
- if(CorsUtils.isPreFlightRequest(request)) {
- return PREFLIGHT_AMBIGUOUS_MATCH;
- }
- AbstractHandlerMethodMapping.Match secondBestMatch = (AbstractHandlerMethodMapping.Match)matches.get(1);
- if(comparator.compare(bestMatch, secondBestMatch) == 0) {
- Method m1 = bestMatch.handlerMethod.getMethod();
- Method m2 = secondBestMatch.handlerMethod.getMethod();
- throw new IllegalStateException("Ambiguous handler methods mapped for HTTP path \'" + request.getRequestURL() + "\': {" + m1 + ", " + m2 + "}");
- }
- }
- this.handleMatch(bestMatch.mapping, lookupPath, request);
- return bestMatch.handlerMethod;
- } else {
- return this.handleNoMatch(this.mappingRegistry.getMappings().keySet(), lookupPath, request);
- }
- }
最终得到了这么一个包含了Handler与这个URI具体处理方法的一个HandlerMethod对象。注意现在这个handler可能还没有被创建出来或者说没有得到,只是知道它的beanName。最终还要调用这么一个createWithResolvedBean方法来得到。
获得了这个handler之后,又继续根据这个handler获得了HandlerExecutionChain。
- public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
- Object handler = this.getHandlerInternal(request);
- if(handler == null) {
- handler = this.getDefaultHandler();
- }
- if(handler == null) {
- return null;
- } else {
- if(handler instanceof String) {
- String executionChain = (String)handler;
- handler = this.obtainApplicationContext().getBean(executionChain);
- }
- HandlerExecutionChain executionChain1 = this.getHandlerExecutionChain(handler, request);
- if(CorsUtils.isCorsRequest(request)) {
- CorsConfiguration globalConfig = this.globalCorsConfigSource.getCorsConfiguration(request);
- CorsConfiguration handlerConfig = this.getCorsConfiguration(handler, request);
- CorsConfiguration config = globalConfig != null?globalConfig.combine(handlerConfig):handlerConfig;
- executionChain1 = this.getCorsHandlerExecutionChain(request, executionChain1, config);
- }
- return executionChain1;
- }
- }
所以得出最终结论getHandler这个方法最终所有通过这个URI返回了一个最开始注册的handler,然后通过 这个handler返回了一个包含这这个HandlerMethod以及一个拦截器链的这么一个对象。之后执行前置拦截器,handler方法,后置拦截,完成。