2016-03-10 51 views
4

我是一个完整的初学者,正在学习构建一个RESTful Web服务。我想知道如何为JAX-RS中的子资源内的子资源设置路径。如何为JAX-RS中的子资源内的子资源设计路径?

我有三个资源:配置文件,消息和评论。 我想我的网址如下。

对于型材

/profiles 

的消息

/profiles/{profileName}/messages 

注解

/profiles/{profileName}/messages/{messageId}/comments 

我的资源具有路径如下。

资料资源

@Path("/profiles") 
public class ProfileResource { 

    @Path("/{profileName}/messages") 
    public MessageResource getMessageResource() { 
     return new MessageResource(); 
    } 

} 

消息资源

@Path("/") 
public class MessageResource { 
    @Path("/{messageId}/comments") 
    public CommentResource getCommentResource() { 
     return new CommentResource(); 
    } 

    @POST 
    @Produces(MediaType.APPLICATION_JSON) 
    @Consumes(MediaType.APPLICATION_JSON) 
    public Message addMessage(@PathParam("profileName") String profileName, Message message){ 
     return messageService.addMessage(profileName, message); 
    } 
} 

评论资源

@Path("/") 
public class CommentResource { 

    @POST 
    @Consumes(MediaType.APPLICATION_JSON) 
    @Produces(MediaType.APPLICATION_JSON) 
    public Comment postComment(@PathParam("messageId") long messageId, Comment comment) { 
     return commentService.addComment(messageId, comment); 
    } 

} 

,但我得到了下面的错误,

SEVERE: Servlet [Jersey Web Application] in web application [/messenger] threw 
load() exception org.glassfish.jersey.server.model.ModelValidationException: 
Validation of the application resource model has failed during application 
initialization. 
[[FATAL] A resource model has ambiguous (sub-)resource method for HTTP method POST 
    and input mime-types as defined by"@Consumes" and "@Produces" annotations at 
Java methods public sokkalingam.restapi.messenger.model.Message 
sokkalingam.restapi.messenger.resources.MessageResource.addMessage(java.lang.Strin 
g,sokkalingam.restapi.messenger.model.Message) and public 
sokkalingam.restapi.messenger.model.Comment 
sokkalingam.restapi.messenger.resources.CommentResource.postComment(long,sokkaling 
am.restapi.messenger.model.Comment) at matching regular expression /. These two 
methods produces and consumes exactly the same mime-types and therefore their 
invocation as a resource methods will always fail.; 

问题:

  1. 应该如何设置我的路径,我的子资源?

  2. 什么是更好的方式来做子资源内的子资源?子资源内的子资源是否共用 ?

回答

3

我应该如何设置我的路我的子资源?

摆脱子资源类上的@Path。当该类用路径注释时,它将作为根资源添加到Jersey应用程序。所以,你有一堆映射到/资源,这是给错误的,因为有多个@POST(与相同@Consumes@Produces)映射到相同的路径

随着子资源类,你不需要@Path。就子资源路径而言,它将被忽略。

什么是更好的方式来做子资源内的子资源?在子资源中执行子资源是否很常见?

我没有看到你在做什么的问题。