使用多态父方法。
@Controller
public class CommentsController {
@RequestMapping(value="/comments", method = RequestMethod.GET)
public @ResponseBody String index() {
/* kludge to allow optional path parameters */
return index(null, null);
}
@RequestMapping(value="/{parent_collection}/{parent_id}/comments", method = RequestMethod.GET)
public @ResponseBody String index(@PathVariable("parent_collection") String parentCollection, @PathVariable("parent_id") String parentId) {
if (parentCollection == null) {
return "all comments";
}
else if ((parentCollection != null) && (parentCollection.equals("posts"))) {
/* get parent, then get comments for parent */
return "comments for single post";
}
else if ((parentCollection != null) && (parentCollection.equals("customers"))) {
/* get parent, then get comments for parent */
return "comments for single customer";
}
else if ((parentCollection != null) && (parentCollection.equals("movies"))) {
/* get parent, then get comments for parent */
return "comments for single movie";
}
}
@RequestMapping(value = "/comments/{id}", method = RequestMethod.GET)
public @ResponseBody String show(@PathVariable Integer id) {
/* kludge to allow optional path parameters */
return show(null, null, id);
}
@RequestMapping(value = "/{parent_collection}/{parent_id}/comments/{id}", method = RequestMethod.GET)
public @ResponseBody String show(@PathVariable("parent_collection") String parentCollection, @PathVariable("parent_id") String parentId, @PathVariable Integer id) {
/* get comment, then get parent from foreign key */
if (parentCollection == null) {
return "single comment";
}
else if ((parentCollection != null) && (parentCollection.equals("posts"))) {
return "single comment for single post";
}
else if ((parentCollection != null) && (parentCollection.equals("customers"))) {
return "single comment for single customer";
}
else if ((parentCollection != null) && (parentCollection.equals("movies"))) {
return "single comment for single movie";
}
}
}
此外,可以使用基本控制器将 URI 前缀路由到父资源 (),将父模型添加到请求范围,然后让常规请求映射处理到子资源的 URI 的其余部分 ()。我没有现成的例子。/libraries/{library_id}/../..
/../../books/1
附注。单一嵌套资源通常被视为 URI 设计的反模式。控制器应处理自己的资源。最常见的实现使单一嵌套资源的密钥唯一,即不依赖于其父资源。例如,数据库记录主键。但是,在某些情况下,键可能不是唯一的,例如序数或位置值(例如,书籍1,第1章,第2章),甚至可能是自然键(例如,书籍ISBN,个人SSN,电子邮件地址,用户名,文件名)。
嵌套资源的规范 URI 示例:
-
/articles
=> 文章控制器#索引
-
/articles/1
=> 文章控制器#显示
-
/articles/1/comments
=> 评论控制器#索引
-
/articles/1/comments/2
=> CommentsController#show(好的,但不是首选)
-
/comments/2
=> 评论控制器#显示(首选)