Sajith Vijesekara
Sajith Vijesekara

Reputation: 1372

Dropwizard bean validation not working

I have wrote drop-wizard Get API request and it has GET API request and parameter list.So i need to validate those pareamaters So problem is i have use

     @Context UriInfo uriInfo 
        MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters();
    String name = parameters.getFirst("name");
Sample sam = new Sample();
sam.setName(name);

to get parameters. So after getting the parameters i have add @NotNull for mandatory parameters in Object bean.Now when i send null values to those mandatory parameters it is working fine.I want to throw error or something when name have null value.I want to know what is the issue in my approach.

public class Sample {
    @NotNull
    private String name;
    @NotNull
    private String StudentId;

    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Upvotes: 0

Views: 1968

Answers (1)

Yuriy Shuliga
Yuriy Shuliga

Reputation: 66

You have two choices, using JSR-303 Hibernate validation framework, packed with Dropwizard:

  1. Explicit validation, result stored in validate variable, no exception thrown:

    ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
    Validator validator = vf.getValidator();
    
    Set<ConstraintViolation<FormDataContentDisposition>> validate =
        validator.validate(samp);
    
  2. Validation before REST annotated method call, when your bean is an input parameter annotated with @Valid, ConstraintViolationException would be thrown:

    @POST
    @Path("/doPost")
    public void addSample(@Valid Sample sample)
    {
        /* Do something */
    }
    

See more details here.

Upvotes: 3

Related Questions