【发布时间】: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() 中记录一些东西,它会被打印出来吗?
-
不,它不会被打印出来。