【发布时间】:2013-05-24 10:57:55
【问题描述】:
我正在使用 Jersey 来实现一个带有一些嵌套资源的 RESTful 服务。这是我目前拥有的一个基本示例:
@Path("/sites")
public class SiteResource {
@GET
@Path("/{siteId}")
public Site get(@PathParam("siteId") long siteId) {
Site site = // find Site with siteId
if (site == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return site;
}
}
@Path("/sites/{siteId}/articles")
public class ArticleResource {
@GET
@Path("/articleId")
public Article get(@PathParam("articleId") long articleId) {
Article article = // find Article with articleId
if (article == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return article;
}
}
现在假设我有一个带有siteId = 123 的站点和一个带有articleId = 456 的文章。文章资源的正确路径是/sites/123/articles/456。
但在我当前的实现中,siteId 完全无关紧要。您也可以使用/sites/789/articles/456 访问资源。
在ArticleResource#get 方法中,我当然可以检查指定的站点是否存在。但这似乎相当不切实际。如果我添加另一个嵌套资源,我必须重复所有检查。
在我看来,这似乎是一个常见的用例,令我惊讶的是,我没有找到解决此问题的任何来源。所以我想知道我是否完全偏离了轨道,是否有更好的方法来处理嵌套资源。
谢谢!
【问题讨论】:
标签: java web-services rest jersey