问题
I'm using Jersey to implement a RESTful Service with some nested resources. This is a basic example of what I currently have:
@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;
}
}
Now imagine I have a Site with siteId = 123
and an Article with articleId = 456
. The correct Path to the Article resource would be /sites/123/articles/456
.
But in my current implementation the siteId is completly irrelevant. You could also use /sites/789/articles/456
to access the resource.
In the ArticleResource#get
method I could of course check if the specified Site exists. But this seems rather impractical. If I add another nested resource, I'd have to repeat all the checks.
As this seems to me a common use case, it surprises me that I didn't find any source addressing this problem. So I'm wondering if I'm maybe completely off the track and there is a better way handling nested resources.
Thanks!
回答1:
The Article seems to be a child of the Site. So there probably is some kind of relation on the Java and/or database side you can use to get and validate Site and Article.
I'd retrieve the Site including its children and the look if the requested Article is on of those.
If Site and Article where not related, your whole URI scheme would not reflect your resources.
来源:https://stackoverflow.com/questions/16733411/validating-path-to-nested-resource