休息 JAX RS : Jersey : How to read pathparam of root resource in sub resource?

标签 rest jersey jax-rs

我试图读取子资源文件中的根资源路径参数,但出现错误。请帮我。

我遵循的方式是:

根资源服务:

@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/

相关文章:

ios - 在 ios 中从不同的 View Controller (不同时间)多次调用相同的 Web 服务

java - 文件上的 Http 415 使用 Jersey 上传

java - spring(启动)数据的 @Repository 的 Jersey 模拟是什么

java - 表单数据剩余 Web 服务中的德语/特殊字符支持

java - JerseyServlet 在服务器启动时初始化资源

javascript - Mixer Client 接口(interface) Beam 对象不是构造函数

rest - 在tomcat级别处理 "Invalid hex characters in escape"

java - 为第三方创建/公开 Web 服务的设计决策

angular - 预检响应中的 Access-Control-Allow-Headers 不允许请求 header 字段 Access-Control-Allow-Methods

java - 重用 Jackson ObjectMapper 和 JsonFactory 实例