REST JAX RS:Jersey:如何读取子资源中root资源的pathparam?

时间:2016-04-19 12:18:03

标签: rest jersey jax-rs

我正在尝试读取子资源文件中的根资源路径参数,但是我收到错误。请帮我。

我关注的方式是:

Root资源服务:

@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);
    }
}

在阅读&#34; messageId&#34;子资源中的路径参数我收到错误:

  

错误:@PathParam值&#39; messageId&#39;与java方法的任何@Path注释模板参数不匹配&#39; getCommentForAMessage&#39;及其封闭的java类型    &#39; org.ramesh.jrs.Messenger.resources.CommentResource&#39;

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

如果要将参数传递给资源类,则必须使用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);
    }

}