解决@PathVariable路径传参带斜杠/的问题

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博客

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值