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.
}
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?
}
Can DropWizard/Jersey be configured to validate my widget
instance, without me having to write any validation code here?
Validation is the process of verifying that some data obeys one or more pre-defined constraints. It is, of course, a very common use case in most applications. The Java Bean Validation framework (JSR-380) has become the de-facto standard for handling this kind of operations in Java.
To validate these entity classes, use the @Valid annotation on the method parameter. For example, the following class is a user-defined class containing both standard and user-defined validation constraints.
JavaBeans Validation (Bean Validation) is a new validation model available as part of Java EE 6 platform. The Bean Validation model is supported by constraints in the form of annotations placed on a field, method, or class of a JavaBeans component, such as a managed bean. Constraints can be built in or user defined.
The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.
Add @Valid
before @PathParam
to validate with Jersey.
See https://jersey.java.net/documentation/latest/bean-validation.html#d0e12201
You may have to do some configuration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With