You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中如何匹配REST URL的嵌套路径参数及空路径?

Spring Boot中匹配REST嵌套路径及空路径的实现方式

在Spring Boot中可以直接通过Spring MVC的路径匹配规则实现你的需求,具体方案如下:

核心实现思路

利用Spring MVC的**通配符匹配任意数量的路径段(包括零段),结合@PathVariable捕获路径参数,同时通过多路径映射支持空路径的匹配。

代码示例

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FileController {

    @GetMapping({"/files", "/files/{path:**}"})
    public String handleFileRequests(@PathVariable(required = false) String path) {
        if (path == null) {
            // 处理访问 /files 的空路径场景
            return "当前访问文件根目录";
        } else {
            // 捕获到的嵌套路径为 folder_1/folder_2/a.sh(无开头斜杠)
            // 如需完整路径格式,可拼接前缀:"/" + path
            String fullNestedPath = "/" + path;
            return "捕获的嵌套路径:" + fullNestedPath;
        }
    }
}

关键细节说明

  • {path:**} 是Spring MVC的路径变量语法,** 用于匹配任意数量的后续路径段(包括0个);
  • 通过@PathVariable(required = false)允许path参数为空,对应访问/files的场景;
  • 当访问/files/folder_1/folder_2/a.sh时,path会被赋值为folder_1/folder_2/a.sh,如果需要带开头的斜杠,自行拼接即可;
  • **通配符只能放在路径变量的末尾,不能用于路径中间的匹配。

内容的提问来源于stack exchange,提问作者zjffdu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 00:30:42