SpringMVC 如何将请求找到匹配的处理方法

本文探讨了SpringMVC框架下,浏览器请求如何被映射到对应的Controller处理方法。在web服务器启动时,Spring容器构建了一个包含controller和URL映射关系的map。初始化过程中,AbstractHandlerMethodMapping的initHandlerMethods方法和getMappingForMethod方法起关键作用,创建RequestMappingInfo对象。DispatcherServlet通过doService方法调用lookupHandlerMethod来确定处理请求的方法,此过程涉及handlermethods、urlMap和nameMap三个关键映射。文章未深入分析类和方法同时有@RequestMapping注解时的情况以及多个匹配方法的排序机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在SpringMVC的模式下,浏览器的一个请求是如何映射到指定的controller的呢?

初始化映射关系

在web服务器启动时,Spring容器中会保存一个map的数据结构,里边记录这controller和url请求中的对应关系。那么这个map中的数据是如何来的呢?

首先来看AbstractHandlerMethodMapping的initHandlerMethods方法(至于为什么直接找到这个方法,我也是网上搜索的,之前的调用链没去纠结)

protected void initHandlerMethods() {
	if (logger.isDebugEnabled()) {
			logger.debug("Looking for request mappings in application context: " + getApplicationContext());
		}

        //获取Spring容器装配的所有bean的名称
	String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?
				BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
				getApplicationContext().getBeanNamesForType(Object.class));

           //遍历
	for (String beanName : beanNames) {
                //判断该bean是否有@controller或者@RequestMapping注解
		if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX) &&
				isHandler(getApplicationContext().getType(beanName))){
                        //如果有上述注解,则需要保存对应关系
			detectHandlerMethods(beanName);
		}
	}
	handlerMethodsInitialized(getHandlerMethods());
}
protected void detectHandlerMethods(final Object handler) {
        //获取传过来handler的类信息
	Class<?> handlerType =
			(handler instanceof String ? getApplicationContext().getType((String) handler) : handler.getClass());

	// Avoid repeated calls to getMappingForMethod which would rebuild RequestMappingInfo instances
        //初始化一个保存映射信息的map
	final Map<Method, T> mappings = new IdentityHashMap<Method, T>();
	final Class<?> userType = ClassUtils.getUserClass(handlerType);

	Set<Method> methods = HandlerMethodSelector.selectMethods(userType, new MethodFilter() {
		@Override
		public bo
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值