【问题标题】:How to parse RESTful API params with Dropwizard如何使用 Dropwizard 解析 RESTful API 参数
【发布时间】:2017-03-27 22:29:16
【问题描述】:

假设我有:

@GET
public UserList fetch(@PathParam("user") String userId) {
    // Do stuff here
}

现在,假设我有自己的userId 类型,我们称之为UserId。当String 被传递到fetch 方法时,是否可以将String 解析为UserId,即:

@GET
public UserList fetch(@PathParam("user") UserId userId) {
    // Do stuff here
}

我意识到我可以在方法内部解析字符串,但我的方法获得我想要的类型会更方便。

【问题讨论】:

    标签: java rest jersey-2.0 dropwizard


    【解决方案1】:

    好吧,您尝试使用请求正文进行 GET 调用,但我认为这不是很有帮助。请阅读 Paul 的 answer here -

    您可以使用 GET 发送正文,但不,这样做从来没有用处

    最好的做法是,如下进行 PUT 或 POST 调用 (PUT vs POST in REST) -

    @POST
    @Path("/some-path/{some-query-param}")
    public Response getDocuments(@ApiParam("user") UserId userId,
                                 @PathParam("some-query-param") String queryParam) {
        UserId userIdInstance = userId; // you can use the request body further
    

    注意 - 使用的 ApiParam 注释是从 com.wordnik.swagger.annotations 包中导入的。您可以根据输入来源类似地使用FormParam,QueryParam

    【讨论】:

      【解决方案2】:

      Dropwizard is using Jersey 用于 HTTPJava POJO 编组。您可以将 Jersey @*Param(@FormParam、@QueryParam 等)中的各种注释用于某些参数。

      如果您需要在 Java POJO 之间使用 map/marshall,请查看test cases in Dropwizard

      @Path("/valid/")
      @Produces(MediaType.APPLICATION_JSON)
      @Consumes(MediaType.APPLICATION_JSON)
      public class ValidatingResource {
          @POST
          @Path("foo")
          @Valid
          public ValidRepresentation blah(@NotNull @Valid ValidRepresentation representation, @QueryParam("somethingelse") String xer) {
              return new ValidRepresentation();
          }
      

      这定义了一个响应 HTTP POST 方法的 API 端点,该方法需要 ValidRepresentation 对象和“somethingelse”作为 HTTP 方法查询参数。端点仅在提供 JSON 参数时才会响应,并且仅返回 JSON 对象(类级别的@Produces 和@Consumes)。 @NotNull 要求该对象是强制调用才能成功,@Valid 指示 Dropwizard 调用 Hibernate 验证器以在调用端点之前验证该对象。

      ValidRepresentation 类是here:

      package io.dropwizard.jersey.validation;
      
      import com.fasterxml.jackson.annotation.JsonProperty;
      import org.hibernate.validator.constraints.NotEmpty;
      
      public class ValidRepresentation {
          @NotEmpty
          private String name;
      
          @JsonProperty
          public String getName() {
              return name;
          }
      
          @JsonProperty
          public void setName(String name) {
              this.name = name;
          }
      }
      

      POJO 使用 Jackson 注释来定义这个对象的 JSON 表示应该是什么样子。 @NotEmtpy 是来自 Hibernate 验证器的注解。

      Dropwizard、Jersey 和 Jackson 负责处理细节。所以对于基本的东西,这就是你所需要的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-31
        • 2017-07-11
        • 2011-11-20
        • 1970-01-01
        相关资源
        最近更新 更多