1、SpringBoot版本:v2.7.2
2、JDK版本:1.8
3、先上解决方案:
@GetMapping("test{path}/**") public Result getMockData(@PathVariable("path") String path, HttpServletRequest request) { final String pathq = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString(); final String bestMatchingPattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString(); String arguments = new AntPathMatcher().extractPathWithinPattern(bestMatchingPattern, pathq); String moduleName; if (StringUtils.isNotBlank(arguments)) { moduleName = '/' + path + '/' + arguments; } else { moduleName = path; } return service.getTestData(moduleName); }
问题描述:在接口路径中传参,参数中带有“/”,导致查询接口404。我path中传的是这种“/test/api”,所以moduleName='/' + path + '/' + arguments,如果传参是这种“test/api”,moduleName=path + '/' + arguments。
4、原因:后续补充
5、参考文章:https://www.jb51.net/article/226814.htm
引申:路径参数中能带两个斜杠//吗
URI的RFC3986规范里,对请求路径( https://datatracker.ietf.org/doc/html/rfc3986#section-3.3,章节3.3 Path)有如下说明:
If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character. If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//"). In addition, a URI reference (Section 4.1) may be a relative-path reference, in which case the first path segment cannot contain a colon (":") character. The ABNF requires five separate rules to disambiguate these cases, only one of which will match the path substring within a given URI reference. We use the generic term "path component" to describe the URI substring matched by the parser to one of these rules.
翻译为:
如果URI包含权限组件,则路径组件必须为空或以斜杠(“/”)字符开头。如果URI不包含授权组件,则路径不能以两个斜杠字符(“/”)开头。此外,URI引用(第4.1节)可以是相对路径引用,在这种情况下,第一个路径段不能包含冒号(“:”)字符。ABNF需要五个独立的规则来消除这些情况的歧义,其中只有一个规则将匹配给定URI引用中的路径子字符串。我们使用通用术语“路径组件”来描述由解析器匹配到这些规则之一的URI子字符串。
就是说,
通常情况下,RFC3986规范不允许url路径里包含两个斜杠“//”。
参考文章:IDEA中用jetty启动web项目时,url路径包含双斜杠会返回404 (url里多了一个斜杠/, jetty返回404,tomcat正常)_mb62c4f25f86c04的技术博客_51CTO博客