• Spring MVC注解Controller源码流程解析---请求匹配中的容错处理



    引言

    Spring MVC注解Controller源码流程解析–映射建立

    Spring MVC注解Controller源码流程解析–定位HandlerMethod

    前面两篇已经对注解版本Controller中映射建立和定位HandlerMethod的过程进行了详细的解析,但是在定位HandlerMethod的过程中,其实有一个小知识没有讲,是关于请求匹配部分细节内容,了解这部分内容可以帮助我们更好弄清楚spring mvc在请求路径匹配问题上的一些优化处理,避免写业务代码过程中犯错。


    spring mvc对于请求路径匹配过程中的容错处理

    Spring MVC注解Controller源码流程解析–定位HandlerMethod章节讲到过,当一个请求发出来时,首先会被RequestMappingHandlerMapping拦截,然后调用lookupHandlerMethod方法,去寻找能够处理当前请求的HandlerMethod。

    而在lookupHandlerMethod方法中,又会在addMatchingMappings方法中,通过间接调用RequestMappingInfo的getMatchingCondition方法,通过RequestMappingInfo自身保存的各类条件信息对当前request请求进行匹配,如果其中有一个条件不满足,那么直接返回null,不会加入matches集合中去。

    在众多条件匹配过程中,与本节相关的就是路径条件匹配,如下:

    		PatternsRequestCondition patterns = null;
    		if (this.patternsCondition != null) {
    			patterns = this.patternsCondition.getMatchingCondition(request);
    			if (patterns == null) {
    				return null;
    			}
    		}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    所以,关键加在于patternsCondition.getMatchingCondition方法,该方法内部到底为我们的请求路径匹配做了哪些容错处理。


    请求匹配过程分析

    	public PatternsRequestCondition getMatchingCondition(HttpServletRequest request) {
    	    //简单的取出request对象属性集合中的PATH_ATTRIBUTE属性
    	    //该属性是在AbstractHandlerMethodMapping#getHandlerInternal方法初始解析请求路径完成后,被放入request属性集合中去的
    	    //lookuppath默认是去除掉context-path后剩下的路径 
    		String lookupPath = UrlPathHelper.getResolvedLookupPath(request);
    		//拿着lookuppath与当前patternsCondition内部的patterns属性集合进行匹配
    		List<String> matches = getMatchingPatterns(lookupPath);
    		//返回的结果也就是匹配上patterns集合中的哪些请求路径
    		return !matches.isEmpty() ? new PatternsRequestCondition(new LinkedHashSet<>(matches), this) : null;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    可以看出来,getMatchingPatterns(lookupPath) 方法才是请求匹配过程中的核心:

    	public List<String> getMatchingPatterns(String lookupPath) {
    		List<String> matches = null;
    		//遍历内部的patterns集合,也就是@RequestMapping注解中我们设置的patterns或者默认value属性值
    		//一个@RequestMapping注解中可以写多个请求路径映射
    		for (String pattern : this.patterns) {
    		     //进行挨个匹配,没匹配上,返回null
    			String match = getMatchingPattern(pattern, lookupPath);
    			//匹配上了,加入match集合
    			if (match != null) {
    				matches = (matches != null ? matches : new ArrayList<>());
    				matches.add(match);
    			}
    		}
    		//如果集合为空,返回空集合
    		if (matches == null) {
    			return Collections.emptyList();
    		}
    		//如果存在多个路径匹配上了,那么需要进行路径排序,让最佳匹配放在最前面
    		if (matches.size() > 1) {
    			matches.sort(this.pathMatcher.getPatternComparator(lookupPath));
    		}
    		return matches;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    spring mvc对于路径匹配上提供的容错处理,其实就体现在了getMatchingPattern方法中,我们下面来具体看看:

    	@Nullable
    	private String getMatchingPattern(String pattern, String lookupPath) {
    	   //如果是精确匹配上了,那么直接返回
    		if (pattern.equals(lookupPath)) {
    			return pattern;
    		}
    		//是否开启后缀匹配---默认是关闭的
    		if (this.useSuffixPatternMatch) {
    		    //fileExtensions是我们可以设置的后缀集合,例如: .doc ; .html ; .js ; .do等后缀集合
    		    //当前请求必须是存在后缀的
    			if (!this.fileExtensions.isEmpty() && lookupPath.indexOf('.') != -1) {
    				for (String extension : this.fileExtensions) {
    				   //如果设置了相关后缀,那么尝试让当前pattern加上后缀后,在于当前请求路径进行模糊匹配
    				   //这里采用的是pathMatcher--实际是AntPathMatcher,会进行ant风格路径匹配
    					if (this.pathMatcher.match(pattern + extension, lookupPath)) {
    						return pattern + extension;
    					}
    				}
    			}
    			else {
    			//如果我们没有指定后缀集合
    			//那么先判断当前请求是否存在后缀
    				boolean hasSuffix = pattern.indexOf('.') != -1;
    				//利用.*后缀进行ant风格匹配
    				if (!hasSuffix && this.pathMatcher.match(pattern + ".*", lookupPath)) {
    					return pattern + ".*";
    				}
    			}
    		}
    		//进行ant风格路径匹配,例如: *,?等符合
    		if (this.pathMatcher.match(pattern, lookupPath)) {
    			return pattern;
    		}
    		//useTrailingSlashMatch功能是默认开启的,该功能的可以让我们使用/hello/请求也能匹配上/hello请求
    		if (this.useTrailingSlashMatch) {
    		     //如果pattern不是以/结尾的,那么尝试加上/之后,再去匹配当前请求路径
    			if (!pattern.endsWith("/") && this.pathMatcher.match(pattern + "/", lookupPath)) {
    				return pattern + "/";
    			}
    		}
    		return null;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    getMatchingPattern中完成了ant风格路径匹配,后缀匹配(默认不开启),useTrailingSlashMatch匹配等容错处理。


    溯源和请求前缀设置

    关于useSuffixPatternMatch和useTrailingSlashMatch属性的提供,其实是在RequestMappingHandlerMapping中提供的:

    在这里插入图片描述

    我们可以看到RequestMappingHandlerMapping中还给我们提供了一个pathPrefixs的设置,那么该属性集合的作用是什么呢?

    还记得在映射建立的过程中,我们需要为当前方法生成一个生成一个映射的接口吗?

    不清楚,回看: Spring MVC注解Controller源码流程解析–映射建立

    	@Override
    	@Nullable
    	protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
    		RequestMappingInfo info = createRequestMappingInfo(method);
    		if (info != null) {
    			RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);
    			if (typeInfo != null) {
    				info = typeInfo.combine(info);
    			}
    			//判断我们是否给当前handler设置了前缀
    			String prefix = getPathPrefix(handlerType);
    			if (prefix != null) {
    			//如果确实设置了前缀,那么:
    			//先为当前前缀简单创建一个ReuqestMappingInfo: 
    			//RequestMappingInfo.paths(prefix).options(this.config).build()
    			//然后再与当前RequestMappingInfo合并
    			//这里合并的主要就是请求路径了,会将请求前缀加在当前请求路径的前面
    				info = RequestMappingInfo.paths(prefix).options(this.config).build().combine(info);
    			}
    		}
    		return info;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    RequestMappingInfo封装的是请求匹配条件,而所谓的combine合并过程,就是将请求匹配条件进行合并。


    获取请求前缀的过程其实也没有那么直接,也会经过一些处理:

    	@Nullable
    	String getPathPrefix(Class<?> handlerType) {
    	    //遍历请求前缀集合
    		for (Map.Entry<String, Predicate<Class<?>>> entry : this.pathPrefixes.entrySet()) {
    			//判断当前请求前缀对应的handler类型是否与传入的一致--》由于这里test其实是一个函数式接口
    			//因此,我们完全可以将一个请求前缀与多个handler相对应,将匹配逻辑写在函数式接口中即可
    		    //只需要确保当前传入的handler类型匹配上我们提供的某个handler时,返回true即可
    			if (entry.getValue().test(handlerType)) {
    				String prefix = entry.getKey();
    				//返回请求前缀时,会经过el解析器解析,因此请求前缀中也可以包含el表达式
    				if (this.embeddedValueResolver != null) {
    					prefix = this.embeddedValueResolver.resolveStringValue(prefix);
    				}
    				return prefix;
    			}
    		}
    		return null;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    Springboot中如何修改springmvc相关配置

    我们上面讲的那些属性和前缀集合如何在springboot环境下进行修改呢?

    我们可以通过继承WebMVCConfigure接口,然后重写其对应的默认方法,完成修改:

    @Configuration
    @RequiredArgsConstructor
    public class MvcConfig implements WebMvcConfigurer{
        
        @Override
        public void configurePathMatch(PathMatchConfigurer configurer) {
            configurer.setUseSuffixPatternMatch(true);
            configurer.addPathPrefix("/back",handlerType ->{
               return handlerType.equals(AdminController.class); 
            });
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    不知道,大家有没有想过,为什么我们实现了WebMvcConfigurer接口,然后将该bean注入容器,就可以完成对Spring mvc想过组件的修改呢?

    这里我简单带领大家过一下源码,看看其中的原理大概是什么样的:


    通过代理完成对默认组件修改

    • WebMvcConfigurerComposite: 内部通过一个List集合管理多个WebMvcConfigurer,实现了WebMvcConfigurer接口,并重写了该接口内部的所有方法,每个重写方法的实现逻辑一致,如下:
      在这里插入图片描述
    	@Override
    	public void configurePathMatch(PathMatchConfigurer configurer) {
    		for (WebMvcConfigurer delegate : this.delegates) {
    			delegate.configurePathMatch(configurer);
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    就是将方法,代理给内部集合中每一个WebMvcConfigurer进行处理。

    • DelegatingWebMvcConfiguration:内部维护了一个WebMvcConfigurerComposite,会搜集所有注入到容器中的WebMvcConfigurer实现类,然后都加入到WebMvcConfigurerComposite的集合中去
      在这里插入图片描述

    DelegatingWebMvcConfiguration继承了WebMvcConfigurationSupport类,该类是完成SpringBoot中完成SpringMVC相关组件默认配置的核心,该类内部对RequestMappingHandlerMapping 的配置代码如下:

    	@Bean
    	@SuppressWarnings("deprecation")
    	public RequestMappingHandlerMapping requestMappingHandlerMapping(
    			@Qualifier("mvcContentNegotiationManager") ContentNegotiationManager contentNegotiationManager,
    			@Qualifier("mvcConversionService") FormattingConversionService conversionService,
    			@Qualifier("mvcResourceUrlProvider") ResourceUrlProvider resourceUrlProvider) {
    
    		RequestMappingHandlerMapping mapping = createRequestMappingHandlerMapping();
    		mapping.setOrder(0);
    		//其他配置不看,就以拦截器配置为例,我们看看具体是如何完成拦截器配置的,以及如何暴露给用户自定义添加拦截器的接口的
    		mapping.setInterceptors(getInterceptors(conversionService, resourceUrlProvider));
            ...         
    		return mapping;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    	protected final Object[] getInterceptors(
    			FormattingConversionService mvcConversionService,
    			ResourceUrlProvider mvcResourceUrlProvider) {
    
    		if (this.interceptors == null) {
    			InterceptorRegistry registry = new InterceptorRegistry();
    			//该方法是暴露给用户增加拦截器的钩子函数
    			addInterceptors(registry);
    			registry.addInterceptor(new ConversionServiceExposingInterceptor(mvcConversionService));
    			registry.addInterceptor(new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider));
    			this.interceptors = registry.getInterceptors();
    		}
    		return this.interceptors.toArray();
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    addInterceptors钩子函数在WebMvcConfigurationSupport中是空实现,子类DelegatingWebMvcConfiguration实现了该钩子方法。

    	@Override
    	protected void addInterceptors(InterceptorRegistry registry) {
    		this.configurers.addInterceptors(registry);
    	}
    
    • 1
    • 2
    • 3
    • 4

    到这里,我相信各位应该都基本明白了,我们为什么能够通过实现WebMvcConfigurer接口修改springmvc的配置了吧。


  • 相关阅读:
    笔记本无线网卡MAC一直改动
    算法通关村-----滑动窗口高频问题
    qiankun项目搭建手册
    完美解决api-ms-win-crt-runtime-l1-1-0.dll详细步骤
    吉时利 Keithley 2700数据采集器技术参数
    【Embedded System】裸机接口开发
    rtl 开发必会技能
    路由导航的时候判断,【每次路由跳转的时候都会调用角色权限的接口】
    C#委托传值
    java计算机毕业设计Web好好吃查询系统源码+mysql数据库+系统+lw文档+部署
  • 原文地址:https://blog.csdn.net/m0_53157173/article/details/126673896