Spring Boot源码之旅二十二SpringMVC源码之DispatcherServlet的getHandler一

作者简介:大家好,我是smart哥,前中兴通讯、美团架构师,现某互联网公司CTO

联系qq:184480602,加我进群,大家一起学习,一起进步,一起对抗互联网寒冬

学习必须往深处挖,挖的越深,基础越扎实!

阶段1、深入多线程

阶段2、深入多线程设计模式

阶段3、深入juc源码解析


阶段4、深入jdk其余源码解析


阶段5、深入jvm源码解析

 

码哥源码部分

码哥讲源码-原理源码篇【2024年最新大厂关于线程池使用的场景题】

码哥讲源码【炸雷啦!炸雷啦!黄光头他终于跑路啦!】

码哥讲源码-【jvm课程前置知识及c/c++调试环境搭建】

 

​​​​​​码哥讲源码-原理源码篇【揭秘join方法的唤醒本质上决定于jvm的底层析构函数】

码哥源码-原理源码篇【Doug Lea为什么要将成员变量赋值给局部变量后再操作?】

码哥讲源码【你水不是你的错,但是你胡说八道就是你不对了!】

码哥讲源码【谁再说Spring不支持多线程事务,你给我抽他!】

终结B站没人能讲清楚红黑树的历史,不服等你来踢馆!

打脸系列【020-3小时讲解MESI协议和volatile之间的关系,那些将x86下的验证结果当作最终结果的水货们请闭嘴】

 

基本流程图,方法查看

DispatcherServlet的doDispatch的核心方法分析

getHandler获取处理器

看起来好像就没多少,其实内部东西还是挺多的,这里就是我们前面初始化的处理器映射器的作用,找到处理器,然后加入拦截器,封装成执行链HandlerExecutionChain 。遍历所有的处理器映射器,找到合适的就返回了。接下去我们看看他们是怎么找的,主要分析RequestMappingHandlerMappingBeanNameUrlHandlerMapping,其他的有兴趣自己可以看,常用的是RequestMappingHandlerMapping

    	@Nullable
    	protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
    		if (this.handlerMappings != null) {
    			for (HandlerMapping mapping : this.handlerMappings) {
    				HandlerExecutionChain handler = mapping.getHandler(request);
    				if (handler != null) {
    					return handler;
    				}
    			}
    		}
    		return null;
    	}

RequestMappingHandlerMapping的getHandler

我们研究一般的流程,不考虑CORS,其实就是尝试获取处理器,这里的处理器其实是封装的方法HandlerMethod,然后进行拦截器的封装。

    	@Override
    	@Nullable
    	public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
    		Object handler = getHandlerInternal(request);
    		if (handler == null) {
    			handler = getDefaultHandler();
    		}
    		if (handler == null) {
    			return null;
    		}
    		// Bean name or resolved handler?
    		if (handler instanceof String) {//如果没有实例化就实例化
    			String handlerName = (String) handler;
    			handler = obtainApplicationContext().getBean(handlerName);
    		}
    		//获取执行链
    		HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
    
    		...
    
    
    		return executionChain;
    	}

AbstractHandlerMethodMapping的getHandlerInternal

核心方法是lookupHandlerMethod

    	@Override
    	protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
    		String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);//获取查找路径
    		request.setAttribute(LOOKUP_PATH, lookupPath);
    		this.mappingRegistry.acquireReadLock();
    		try {
    			HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);//查找方法
    			return (handlerMethod != null ? handlerMethod.createWithResolvedBean() : null);
    		}
    		finally {
    			this.mappingRegistry.releaseReadLock();
    		}
    	}
AbstractHandlerMethodMapping的lookupHandlerMethod

首先去uri映射注册器里找是否有这个方法的集合,有的话直接处理,没有的话就遍历所有的uri处理,找出最匹配的HandlerMethod 返回。

    @Nullable
    	protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
    		List<Match> matches = new ArrayList<>();
    		List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);
    		if (directPathMatches != null) {//有path匹配的直接处理
    			addMatchingMappings(directPathMatches, matches, request);
    		}
    		if (matches.isEmpty()) {//没有就遍历所有的处理
    			// No choice but to go through all mappings...
    			addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, request);
    		}
    
    		if (!matches.isEmpty()) {//有匹配的
    			Match bestMatch = matches.get(0);
    			if (matches.size() > 1) {//多个匹配的情况
    				Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
    				matches.sort(comparator);
    				bestMatch = matches.get(0);
    				if (logger.isTraceEnabled()) {
    					logger.trace(matches.size() + " matching mappings: " + matches);
    				}
    				if (CorsUtils.isPreFlightRequest(request)) {
    					return PREFLIGHT_AMBIGUOUS_MATCH;
    				}
    				Match secondBestMatch = matches.get(1);
    				if (comparator.compare(bestMatch, secondBestMatch) == 0) {
    					Method m1 = bestMatch.handlerMethod.getMethod();
    					Method m2 = secondBestMatch.handlerMethod.getMethod();
    					String uri = request.getRequestURI();
    					throw new IllegalStateException(
    							"Ambiguous handler methods mapped for '" + uri + "': {" + m1 + ", " + m2 + "}");
    				}
    			}//handlerMethod设置到属性里
    			request.setAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE, bestMatch.handlerMethod);
    			handleMatch(bestMatch.mapping, lookupPath, request);
    			return bestMatch.handlerMethod;
    		}
    		else {
    			return handleNoMatch(this.mappingRegistry.getMappings().keySet(), lookupPath, request);
    		}
    	}
MappingRegistry的getMappingsByUrl

这个会先进行uri匹配,如果获取到了就直接返回,那这些uri是怎么来的,我们还是要先弄明白。


下篇介绍下这个uri怎么来的。

  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值