2015-05-25 34 views
1

我试图让我的头在泽西岛的这个RESTful场景中:我有两个资源,用户和项目,并且我想要检索连接到某个用户的所有项目以及所有项目用户连接到某个项目。总之,用户和项目之间存在多对多的关系。连接到某个项目GET .../users/{user_id}/items 以相互交织的方式在泽西交织资源

  • 所有用户:

    • 所有连接到某个用户的项目:GET .../items/{item_id}/users

    我如何能实现

    我碰到这个REST风格的设计都这在泽西岛?我发现this解决方案,但它涉及嵌套在根资源中的子资源,而在我的情况下,用户和项都是可通过自己的URI访问的根资源。

  • 回答

    1

    我决定实现该解决方案建议here,即创建代表上述relantionships特定资源。

    该模型的项目相关的对用户的关系是这样的代码:

    @Path("users/{userId}/items") 
    public class RelatedItemResource { 
    
        @GET 
        @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) 
        public List<Item> getRelatedItems(@PathParam("userId") String userId) { 
         // returns list of related items 
        } 
    
        // Other methods  
    } 
    

    建模的用户相关的对项目的关系是这样的代码:

    @Path("items/{itemId}/users") 
    public class RelatedUserResource { 
    
        @GET 
        @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) 
        public List<User> getRelatedUsers(@PathParam("itemId") String itemId) { 
         // returns the list of related users 
        } 
    
        // Other methods 
    } 
    
    3

    以下应该工作。

    @Path("users") 
    public class UserResource { 
    
        @GET 
        @Consumes(MediaType.APPLICATION_JSON) 
        @Produces(MediaType.APPLICATION_JSON) 
        @Path("{user_id}/items") 
        public Response getItems(@PathParam("user_id") String userId) { 
         //get the items and return a response 
        } 
    } 
    
    @Path("items") 
    public class ItemResource { 
    
        @GET 
        @Consumes(MediaType.APPLICATION_JSON) 
        @Produces(MediaType.APPLICATION_JSON) 
        @Path("{item_id}/users") 
        public Response getUsers(@PathParam("item_id") String itemId) { 
         //get the users and return a response 
        } 
    } 
    
    0

    对于连接到特定项目的所有用户,这听起来更像是一个搜索条件以获取用户列表。所以我会建议这个路径:/users?item={itemid}。鉴于这种表示法,您可以真正构建一个灵活的搜索条件终结点,其中每个查询参数都是可选的,并且如果给定某个值,则会受到尊重。