Jersey/JAX-RS 资源方法输入 bean 验证

我通过 DropWizard 0.7.1 使用 Jersey/JAX-RS 来公开 RESTful 服务端点.我的所有实体 POJO 都使用 JAX-RS 和 Hibernate/JSR-303 bean 验证注释进行了注释,如下所示:

I am using Jersey/JAX-RS via DropWizard 0.7.1 to expose RESTful service endpoints. I have all of my entity POJOs annotated with both JAX-RS and Hibernate/JSR-303 bean validation annotations like so:

public class Widget {
    @JsonProperty("fizz")
    @NotNull
    @NotEmpty
    private String fizz;     // Can't be empty or null

    @JsonProperty("buzz")
    @Min(value=5L)
    private Long buzz;       // Can't be less than 5

    // etc.
}

当资源方法接收这些 POJO 之一作为输入时(实际上,DropWizard 已经将 HTTP 实体 JSON 反序列化为 Widget 实例),我想针对 Hibernate/Bean Validation 注解:

When a resource method receives one of these POJOs as input (under the hood, DropWizard has already deserialized the HTTP entity JSON into a Widget instance), I would like to validate it against the Hibernate/Bean Validation annotations:

@POST
Response saveWidget(@PathParam("widget") Widget widget) {
    // Does DropWizard or Jersey have something built-in to automagically validate the
    // 'widget' instance?
}

是否可以将 DropWizard/Jersey 配置为验证我的 widget 实例,而无需我在这里编写任何验证代码?

Can DropWizard/Jersey be configured to validate my widget instance, without me having to write any validation code here?

推荐答案

@PathParam 之前添加 @Valid 以使用 Jersey 进行验证.

Add @Valid before @PathParam to validate with Jersey.

请参阅 https://jersey.java.net/documentation/latest/bean-validation.html#d0e12201

您可能需要进行一些配置.

You may have to do some configuration.

相关文章