1

我们正在开发基于 REST 的服务,并且我们正在使用 Spring MVC。我们正面临方法解析问题的 url。这大致就是我们正在尝试做的事情

假设我们有人带着他们的宠物

//Class level request mapping
@RequestMapping("/persons")

// Mapping to access a specific person inside one of the methods
@RequestMapping(value="/{personId}", method= RequestMethod.GET
//.... getPerson method


// Mapping to access a specific person's pets inside one of the methods
@RequestMapping(value="/{personId}/pets", method= RequestMethod.GET
// getPersonPets method

如果请求以“/persons/P12323233”的形式出现,其中 P12323233 是人员 ID,它将解析为 getPerson 方法。如果请求以“/persons/P12323233/pets”的形式出现,其中 P12323233 是人员 ID,它会解析为 getPersonPets 方法。

所以到目前为止一切都很好。但是如果请求以“/persons/pets”的形式出现,则请求将解析为 getPerson 方法。虽然我们可以在 getPerson 方法中将其作为错误情况处理,但我们正在尝试检查是否有任何方法可以解决对 getPersonPets 的调用方法。

我们仍在争论处理这种情况的正确位置是 getPerson 还是 getPersonPets 方法。除了争论之外,我们想知道实现 getPersonPets 方法的解析是否在技术上是可行的。

感谢任何帮助。

4

3 回答 3

1

您还可以使用正则表达式并过滤掉 404 等请求。例如:

// Mapping to access a specific person inside one of the methods
@RequestMapping(value="/{personId:P[\\d]+}", method= RequestMethod.GET
//.... getPerson method


// Mapping to access a specific person's pets inside one of the methods
@RequestMapping(value="/{personId:P[\\d]+}/pets", method= RequestMethod.GET
// getPersonPets method
于 2013-08-22T12:01:32.630 回答
1

这可以通过为同一方法添加多个映射来解决:

@RequestMapping(value="/{personId}", method= RequestMethod.GET
//.... getPerson method

@RequestMapping(value = {"/{personId}/pets", "/pets"}, method= RequestMethod.GET
// getPersonPets method

更新:请注意,在访问/pets 时使用以下签名将引发异常,因为URL 中不存在personId :

public String showPets(@PathVariable("personId") long personId)

这将是访问变量的最方便的方法,但鉴于我们有多个路径映射同一个方法,我们可以将签名更改为以下内容以避免出现异常:

public String showPets(@PathVariable Map<String, String> vars)

并从地图中检索路径变量

于 2013-08-22T11:59:07.113 回答
0

尽管通常 REST 假定您在未指定资源上的段时引用 ID,但我喜欢添加 id,以使其余端点不那么模棱两可。

如果允许您更改 API,请考虑执行以下操作:

//Class level request mapping
@RequestMapping("/persons")

// Mapping to access a specific person inside one of the methods
@RequestMapping(value="/id/{personId}", method= RequestMethod.GET
//.... getPerson method


// Mapping to access a specific person's pets inside one of the methods
@RequestMapping(value="/id/{personId}/pets", method= RequestMethod.GET
// getPersonPets method
于 2013-08-22T16:21:16.013 回答