如何在JAX-RS中为子资源设计子资源路径?

时间:2016-03-10 03:24:24

标签: java web-services rest jersey jax-rs

我是一个完全初学者,正在学习构建RESTful Web服务。我想知道如何在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. 在子资源中执行子资源的更好方法是什么?是吗 在子资源中做子资源是常见的吗?

1 个答案:

答案 0 :(得分:3)

  

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

摆脱子资源类的@Path。当使用路径注释类时,它将作为根资源添加到Jersey应用程序中。因此,有一堆资源映射到/,这会产生错误,因为有多个@POST(具有相同的@Consumes@Produces)映射到同一路径

对于子资源类,您不需要@Path。就子资源路径而言,它将被忽略。

  

在子资源中执行子资源的更好方法是什么?在子资源中做子资源是否常见?

我不知道你在做什么有任何问题。