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

Java Spring Boot Swagger中GET请求传递ProductIds列表的实现问题

解决Spring Boot中Swagger GET请求携带ProductIds列表的问题

问题分析

原代码用@PathParam接收List<Long>类型的productIds,但JAX-RS默认不会自动将路径中逗号分隔的字符串(如2%2C3)解析为列表,导致请求路径不匹配,返回404。下面提供两种可行的修改方案:


方案一:修正路径参数的列表解析

如果坚持用路径参数传递列表,需要手动处理逗号分隔的字符串,同时在Swagger注解中明确输入格式:

@GET
@Path("/product/{customerId}/{productIds}")
@ApiOperation(
        value = "获取产品列表",
        response = ProductResponse.class,
        responseContainer = "List"
)
List<ProductResponse> getProductData(
        @ApiParam(value = "客户ID", required = true) @PathParam("customerId") long customerId,
        @ApiParam(value = "产品ID列表,格式为逗号分隔的数字,如2,3", required = true) @PathParam("productIds") String productIdsStr
);

在方法内部将字符串拆分为列表:

List<Long> productIds = Arrays.stream(productIdsStr.split(","))
                              .map(Long::parseLong)
                              .collect(Collectors.toList());

Swagger输入说明:在路径参数的productIds输入框中直接输入逗号分隔的数字,比如2,3,Swagger会自动编码为2%2C3拼入路径。


方案二:改用@RequestParam(查询参数)

这是GET请求传递列表更符合REST规范的方式,Swagger对这种方式的支持更友好:

@GET
@Path("/product/{customerId}")
@ApiOperation(
        value = "获取产品列表",
        response = ProductResponse.class,
        responseContainer = "List"
)
List<ProductResponse> getProductData(
        @ApiParam(value = "客户ID", required = true) @PathParam("customerId") long customerId,
        @ApiParam(value = "产品ID列表,可输入多个值或逗号分隔", required = true) @RequestParam(value = "productIds", required = true) List<Long> productIds
);

Swagger输入说明:

  • 方式1:在Swagger的参数输入区域,点击productIds参数的"添加"按钮,逐个输入产品ID(如2、3),Swagger会自动生成?productIds=2&productIds=3的查询串。
  • 方式2:直接在productIds输入框中输入逗号分隔的数字(如2,3),Spring Boot默认支持将这种格式的字符串直接解析为List<Long>,Swagger也会正确识别并传递参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:40:48