【问题标题】:unlimited number of Path Variables in the form of one URI template一个URI模板形式的无限数量的路径变量
【发布时间】:2014-03-25 19:30:29
【问题描述】:

我现有的代码如下:

@RequestMapping(value = "/{id}/{type}/{answer}", method = RequestMethod.GET)
@ResponseBody
public Results answer(@PathVariable("id") int questionId,
        @PathVariable int type,
        @PathVariable Boolean answer) {

        //do something
}

我希望能够添加使用任意数量的路径变量发出请求的功能,但保持与上述相同的模式(即 /id/type/answer/id/type/answer/id/type/回答/...等)。

因此,理想情况下,我希望能够创建一个支持以下两个 URL 的 API 调用:

http://www.example.com/sendAnswer/id1/typeA/0

http://www.example.com/sendAnswer/id1/typeA/0/id2/typeB/1/id3/typeA/0

有人有什么想法吗?

【问题讨论】:

  • 我们刚刚离开了查询字符串参数。所以我们想保留路径变量。是的,唯一具有多个值的变量是 answers 路径变量......我们将为答案做一个逗号分隔的列表。
  • 理想情况下,我希望能够创建一个支持以下两个 URL 的 API 调用:example.com/sendAnswer/id1/typeA/0example.com/sendAnswer/id1/typeA/0/id2/typeB/1/id3/typeA/0 @ShaunScovil
  • 我认为@PathVariable 无法做到这一点,它使用PathVariableMethodArgumentResolver 来解决它的价值。您可以通过扩展 ArgumentResolver 或子类 AbstractNamedValueMethodArgumentResolver 来实现自己的 ArgumentResolver

标签: java spring rest uritemplate


【解决方案1】:

根据您的 cmets,考虑创建两个端点:

/{id}/{type}/{answerId} 返回一个具体的答案。

/{id}/{type}/answers 返回一个包含所有答案的数组。

在检索多个答案的情况下,您确实应该使用查询参数来过滤结果。像这样的:

/{id}/{type}/answers?ids=1,2,3&types=A,B,C

【讨论】:

  • 正确映射您的两个端点将是一个可怕的问题。如何决定使用哪种模式?
  • @Bart 不错。意思是说/{id}/{type}/answers 用于第二个端点。我已经相应地编辑了我的答案。
猜你喜欢
  • 2012-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多