繁体   English   中英

Java Spring Boot: Swagger GET请求中的列表

[英]Java Spring Boot: Swagger GET List in the Request

我正在尝试在 Java Spring Boot Swagger 中设置 GET 请求,请求中包含 ProductIds 列表。 我如何为此编辑下面的代码?

@GET
@Path("/product/{customerId}/{productIds}")
@ApiOperation(
        value = "Get Products",
        response = ProductResponse.class,
        responseContainer = "List"
)
List<ProductResponse> getProductData(
        @ApiParam(value = "customerId", required = true) @PathParam("customerId") long customerId,
        @ApiParam(value = "productIds", required = true) @PathParam("productIds") List<Long> productIds
);

结果:CustomerId 7 和 ProductIds (2,3)

404 Not Found

http://localhost:50111/product-domain/api/product/7/2%2C3

更新:如果我对 ProductIds 使用 RequestParam,我将如何在 swagger 正文中输入它? 注意:任何解决方案都可以,(不一定需要使用 RequestParam)

   @RequestParam(value="productIds", required=true) List<Long> productIds

在此处输入图像描述

在我看来,在这种情况下,您不应使用 PathVariable,而应使用 RequestParam(最好是 RequestBody)。

在使用 RequestParam 的情况下,它应该是这样的:

@Path("/product/{customerId}")
List<ProductResponse> getProductData(
        @ApiParam(value = "customerId", required = true) @PathParam("customerId") long customerId,
        @ApiParam(value = "productIds", required = true) @RequestParam("productIds") List<Long> productIds
);

比你的 url 看起来像:http://localhost:50111/product-domain/api/product/7?productIds=2,3

在使用 RequestBody 的情况下,它应该是这样的:

@Path("/product/{customerId}")
List<ProductResponse> getProductData(
        @ApiParam(value = "customerId", required = true) @PathParam("customerId") long customerId,
        @ApiParam(value = "productIds", required = true) @RequestBody("productIds") List<Long> productIds
);

比你的 url 看起来像:http://localhost:50111/product-domain/api/product/7 你的 http 请求正文应该包含:[2, 3]

为什么我建议不要在这种情况下使用@PathParam?

  • Url 长度有长度限制(大约 2048 个字符) - 所以如果您以后尝试传递长列表,这可能是个问题
  • Url 需要“规范化”/“转义”特殊字符,这使得 url 对人类来说可读性较差,这是使用 PathParam 的本质

顺便说一句:考虑使用 PathVariable 而不是 PathParam - 因为 PathVariable 来自 Spring,但 PathParam 来自 JAX-RS,我假设你想使用 Spring Boot

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM