【问题标题】:How can i process same URL with different parameters?如何处理具有不同参数的相同 URL?
【发布时间】:2019-05-14 07:01:54
【问题描述】:

我在创建一些 REST-API 时遇到了一些问题。

我希望某些 API 有不同的参数。

例如:

path?include="stack"
path?exclude="overflow"

我想到了两种方法。

  • 首先:Create API 可以接收控制器中的所有参数和进程。
@GetMapping
public ResponseEntity getByFilter(@RequestParam @Nullable final String exclude,
                                  @RequestParam @Nullable final String include){
 // any process to distinguish. 
}
  • 第二:创建多个API可以接收一个参数。
@GetMapping(params = "include")
public ResponseEntity getByInclude(@RequestParam final String include){
// do anything
}

@GetMapping(params = "exclude")
public ResponseEntity getByInclude(@RequestParam final String exclude){
// do anything
}

但两者都有问题。

  • 首先:逻辑将增加参数。

  • 第二:我用于SpringBoot的SwaggerDocument不能支持相同的路径,不同的参数。如果我使用“enableUrlTemplating”,我的团队将手动管理 SwaggerDocument。

我该如何解决这些问题?

感谢阅读。

【问题讨论】:

  • 采用第一种方法,您需要验证只传递一个参数
  • 为什么不创建 2 个不同的 url?例如,第一个可以是/path/include?type="stack",而第二个可以是/path/exclude?type="overflow"
  • @DimitarSpasovski 我想获取“路径”资源,而不是排除或包含。
  • @choihyunjin 你想要只有控制器来做这个吗?

标签: java spring spring-boot swagger-ui


【解决方案1】:

我会选择你的第一个建议,定义你的 @RequestParam 并在代码中,首先检查是否只定义了一个参数。

然后关于 Swagger 文档,您可以添加:

  • 对于每个参数,类似这样的描述@ApiParam(value = "Use this parameter to exclude some resources")
  • 对于端点,@ApiOperation(value = "Endpoint name", notes = "Here you can put the description of the behavior you are expecting, write here if the parameters are to be used at the same time, are mutually exclusive, if you have to set always one...", response = YourResponseDTO.class)

希望有所帮助:-)

【讨论】:

  • 感谢您的回复,但我知道这种方式。我想要其他可以解决我遇到的问题的解决方案。
【解决方案2】:

您只需一个控制器即可完成此操作。像

这样写控制器
@GetMapping
public ResponseEntity getByFilter(@RequestParam(value="exclude", required=false) String exclude,@RequestParam(value="include", required= flase)String include){
 // any process to distinguish. 
}

【讨论】:

  • 感谢您的回复,但我已经在我的问题中这样写了。
  • @choihyunjin 很好!你也可以试试这个方法。也许这也是将来可以帮助您的另一种方式!编码愉快!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
相关资源
最近更新 更多