我试图读取子资源文件中的根资源路径参数,但出现错误。请帮我。
我遵循的方式是:
根资源服务:
@Path("/{messageId}/comments")
public CommentResource getCommentResources(){
return new CommentResource();
}
子资源代码:
@Path("/")
public class CommentResource {
private CommentDAOImpl commentDaoObject = new CommentDAOImpl();
@GET
@Produces(MediaType.APPLICATION_JSON)
public ArrayList<Comment> getAllCommentsForAMessage(@PathParam("messageId") long messageId){
return commentDaoObject.getAllCommentsForMessage(messageId);
}
@Path("/{commentId}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Comment getCommentForAMessage(@PathParam("commentId") long commentId, @PathParam("messageId") long messageId){
return commentDaoObject.getCommentForMessage(messageId, commentId);
}
}
在读取子资源中的“messageId”路径参数时,我收到错误:
Error: @PathParam value 'messageId' does not match any @Path annotation template parameters of the java method 'getCommentForAMessage' and its enclosing java type 'org.ramesh.jrs.Messenger.resources.CommentResource'.
谁能帮我解决这个问题吗?
最佳答案
如果要将参数传递给资源类,则必须使用ResourceContext.initResource method .
这是修改代码的方法:
根资源服务
@Path("/{messageId}/comments")
public CommentResource getCommentResources(@PathParam("messageId") long messageId, @Context ResourceContext resourceContext){
return resourceContext.initResource(new CommentResource(messageId));
}
子资源代码:
public class CommentResource {
private CommentDAOImpl commentDaoObject = new CommentDAOImpl();
private long messageId;
public CommentResource(long messageId) {
this.messageId = messageId;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public ArrayList<Comment> getAllCommentsForAMessage(){
return commentDaoObject.getAllCommentsForMessage(messageId);
}
@GET
@Path("/{commentId}")
@Produces(MediaType.APPLICATION_JSON)
public Comment getCommentForAMessage(@PathParam("commentId") long commentId){
return commentDaoObject.getCommentForMessage(messageId, commentId);
}
}
关于休息 JAX RS : Jersey : How to read pathparam of root resource in sub resource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36718154/