【问题标题】:I am having issue while implementing sub-resources using JAX-RS?我在使用 JAX-RS 实现子资源时遇到问题?
【发布时间】:2018-06-02 09:34:18
【问题描述】:

我想使用 JAX-RS 实现子资源。资源的 URI 将类似于 http://localhost:8080/messenger/webapi/messages/1/comments。 我可以使用以下 URI http://localhost:8080/messenger/webapi/messages/1 获取消息,但是当我尝试获取消息的 cmets 时,我只会得到空花括号。

两个资源类都在同一个包中。我知道如果 URI 的映射不正确,我会收到 404 错误,但会收到 200 个带空括号的状态码。

    @Path("/messages")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class MessageResource {
    MessageService ms = new MessageService();


    @GET
    @Path("/{messageId}")
    public Message getMessage(@PathParam("messageId") long messageId) {
        return ms.getMessage(messageId);
    }

    @POST
    public Message addMessage(Message message) {
        return ms.addMessage(message);
    }

    @PUT
    @Path("/{messageId}")
    public Message updateMessage(@PathParam("messageId") long messageId, Message message) {
        message.setId(messageId);
        return ms.updateMessage(message);
    }

    @DELETE
    @Path("/{messageId}")
    public void deleteMessage(@PathParam("messageId") long messageId) {
        ms.removeMessage(messageId);
    }

    @GET
    @Path("/{messageId}/comments")
    public CommentResource getComments() {
        return new CommentResource();
    }

}

CommentResource 类代码:

public class CommentResource {

private CommentService commentService = new CommentService();

@GET
public String test() {
    return "new sub resource";
}
}

【问题讨论】:

  • 您在评论资源中使用了什么路径?私有的 CommentService 没有目的
  • 我想获取所有 cmets 的消息,例如 messages/1/cmets。
  • 如果你添加一个 System.out.prinln o 在 test() 中记录一些东西,它会被打印出来吗?
  • 不,它不会被打印出来。

标签: java jax-rs tomcat8


【解决方案1】:

我发现我在导致问题的 getComments() 方法上使用了@GET 注释。我已将其删除,现在代码工作正常。

@GET
@Path("/{messageId}/comments")
public CommentResource getComments() {
    return new CommentResource();
}

【讨论】:

  • 但是为什么使用@get 会导致任何问题。如我所见,您仍然提到过。你的意思是在你的 CommentResource 上 GET 吗?
  • @techprat Sub-resource locators 没有 http 方法。该方法只是将调用转发给CommentResource,其方法确实具有Http方法。
猜你喜欢
  • 2013-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多