【问题标题】:Resteasy @path with zero or more path parameters具有零个或多个路径参数的 Resteasy @path
【发布时间】:2012-01-23 13:43:51
【问题描述】:

我在我的 API 开发中使用 RESTEasy。我的网址是http://localhost:8080/project/player/Mhttp://localhost:8080/project/player

这意味着我将 {gender} 作为路径参数。

我的问题是如何将此 url 映射到 REST 方法,我使用下面的映射

@GET
@Path("player/{gender}")
@Produces("application/json")

但是如果使用它,它会映射到http://localhost:8080/project/player/M,而不是http://localhost:8080/project/player。 我需要一个正则表达式来映射零个或多个路径参数

谢谢。

【问题讨论】:

    标签: java url resteasy


    【解决方案1】:

    有什么理由这必须是路径参数而不是查询字符串?如果您将其更改为使用后者,则可以使用@DefaultValue 注释。

    因此您的代码将如下所示:

    @GET
    @Path("player") //example: "/player?gender=F"
    @Produces("application/json")
    public Whatever myMethod(@QueryParam("gender") @DefaultValue("M") final String gender) {
      // your implementation here
    }
    

    【讨论】:

    • 尽管这不是问题的直接答案,但它是正确的做法。 REST 路径不应该有可选部分。我做错了,这个答案“唤醒了我”。
    【解决方案2】:

    路径参数 (@PathParam) 不是可选的。如果你想映射;

    您将需要两种方法。您可以使用方法重载;

    @GET
    @Path("player/{gender}")
    @Produces("application/json")
    public Whatever myMethod(@PathParam("gender") final String gender) {
      // your implementation here
    }
    
    @GET
    @Path("player")
    @Produces("application/json")
    public Whatever myMethod() {
      return myMethod(null);
    }
    

    【讨论】:

    【解决方案3】:

    请参阅下面的链接,其中包含通过正则表达式的可选路径参数示例

    RestEasy @Path Question with regular expression

    【讨论】:

    • 我不建议您使用正则表达式作为路径参数。它只是把一个相对简单的问题复杂化了……
    【解决方案4】:

    当你想在路径中有可选参数时,你应该使用正则表达式。

    因此您的代码将如下所示:

    @GET
    @Path("/player{gender : (/\\w+)?}")
    @Produces("application/json;charset=UTF-8")
    public Whatever myMethod(@QueryParam("gender") @DefaultValue("M") final String gender) {
      // your implementation here
    }
    

    欲了解更多信息,请参阅https://docs.jboss.org/resteasy/docs/1.1.GA/userguide/html/Using__Path_and__GET___POST__etc..html

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 2011-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多