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

如何在Spring中创建支持可变数量路径变量的REST API

在Spring中创建支持可变数量路径变量的REST API

嘿,这个需求其实挺常见的,在Spring框架里有两种简单靠谱的方式实现,我给你一步步讲清楚:

方法一:使用Ant风格通配符 + @PathVariable

Spring支持Ant风格的路径匹配,其中**可以匹配任意深度的路径段,刚好适合你这种分类数量不固定的场景。

实现示例

你可以在控制器方法上用@GetMapping("/{categories:**}")来捕获所有/ads/之后的路径,然后把整个路径字符串拆分成分类数组:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/ads")
public class AdCategoryController {

    @GetMapping("/{categories:**}")
    public List<String> getAdsByCategories(@PathVariable String categories) {
        // 将路径字符串按斜杠拆分,得到所有分类
        String[] categoryList = categories.split("/");
        // 这里可以替换成你的业务逻辑,比如根据分类查询广告
        return Arrays.asList(categoryList);
    }
}

测试示例

  • 当请求GET /ads/electronics,categories的值是electronics,拆分后得到["electronics"]
  • 当请求GET /ads/electronics/laptops/gaming,categories的值是electronics/laptops/gaming,拆分后得到["electronics", "laptops", "gaming"]
  • 当请求GET /ads,categories会是空字符串,拆分后得到一个空数组,记得在业务逻辑里处理这种边界情况哦

注意事项

  • 如果你还有其他更具体的端点(比如/ads/featured),一定要把这个可变路径的方法放在最后定义,不然Spring会优先匹配/**,导致具体端点失效。

方法二:通过HttpServletRequest获取完整路径

如果你不想用路径变量,也可以直接从HttpServletRequest里拿到完整请求路径,再手动截取分类部分:

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/ads")
public class AdCategoryController {

    @GetMapping("/**")
    public List<String> getAdsByCategories(HttpServletRequest request) {
        // 截取"/ads/"之后的路径部分
        String path = request.getRequestURI().substring(request.getContextPath().length() + "/ads/".length());
        // 拆分分类
        String[] categoryList = path.split("/");
        return Arrays.asList(categoryList);
    }
}

这种方式和方法一效果一样,只是获取路径的方式不同,看你个人习惯选择就行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:23:40