【问题标题】:@PathParam as class variable in Jersey@PathParam 作为 Jersey 中的类变量
【发布时间】:2017-09-28 03:49:07
【问题描述】:

我正在使用 Jersey 构建一个 RESTful 服务,并且我有 Servlet,它们在多种方法中使用相同的 PathParam。所以我想将 PathParam 值存储在全局变量中,而不是每个方法中的局部变量中。

类似:

@Path("mensas/{mensaID}/dishes/{dishID}")
public class CommentServlet {
//Global PathParams
@PathParam("mensaID")
long mensaID;
@PathParam("dishID")
long dishID;

@GET
@Path("comments")
public String getDishComments() {
    //  ...
}

}

代替:

@Path("mensas/{mensaID}/dishes/{dishID}")
public class CommentServlet {

    @GET
    @Path("comments")
    //Local PathParams
    public String getDishComments(@PathParam("mensaID") long mensaID, @PathParam("dishID") long dishID) {
        //  ...
    }
}

或者也许还有其他方法可以更好地做到这一点?

【问题讨论】:

  • 只是好奇:您希望从中获得什么?
  • 我只需要在一个地方设置一次值,并且方法的签名会短很多,这是我个人更喜欢的。 (假设结果显然是一样的)
  • 可以的。您只需要确保将您的类注册为类(默认请求范围)而不是单例(或实例)。

标签: java rest jersey


【解决方案1】:

您可以通过将所有参数提取到一个新类来重构您的代码(保留原来的 @PathParam 注释):

public class DishParams {
    @PathParam("mensaID")
    private long mensaID;

    @PathParam("dishID")
    private long dishID;

    public long getMensaID() {
        return mensaID;
    }

    public void setMensaID(long mensaID) {
        this.mensaID = mensaID;
    }

    public long getDishID() {
        return dishID;
    }

    public void setDishID(long dishID) {
        this.dishID = dishID;
    }
}

然后使用前面提到的带有@BeanParam注解的类声明一个参数

public class CommentServlet {

    @GET
    @Path("comments")
    public String getDishComments(@BeanParam DishParams params) {
        // ...
        return null;
    }
}

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    • 2016-01-01
    相关资源
    最近更新 更多