Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey/JAX-RS resource method input bean validation

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?

like image 955
IAmYourFaja Avatar asked Dec 09 '14 21:12

IAmYourFaja


People also ask

What is Jersey bean validation?

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.

How will you enable validation on the resource in the following bean class?

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.

How can you explain Bean validation?

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.

What does @NotNull annotation mean in bean property?

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.


1 Answers

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.

like image 173
Adam Avatar answered Oct 17 '22 10:10

Adam