验证嵌套资源的路径 [英] Validating path to nested resource

查看:43
本文介绍了验证嵌套资源的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jersey来实现一些嵌套资源的RESTful服务.这是我目前拥有的一个基本示例:

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;
    }
}

现在想象一下,我有一个站点和一个siteId = 123以及一个文章和articleId = 456.文章资源的正确路径为/sites/123/articles/456. 但是在我当前的实现中,siteId完全无关紧要.您还可以使用/sites/789/articles/456来访问资源.

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.

ArticleResource#get方法中,我当然可以检查指定的Site是否存在.但这似乎是不切实际的.如果添加另一个嵌套资源,则必须重复所有检查.

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.

谢谢!

推荐答案

该文章似乎是网站的子级.因此,在Java和/或数据库方面可能存在某种关系,您可以用来获取和验证站点和文章.

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.

如果站点"和文章"不相关,则您的整个URI方案将不会反映您的资源.

If Site and Article where not related, your whole URI scheme would not reflect your resources.

这篇关于验证嵌套资源的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆