簡體   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