How do I use Custom Validations in Jersey

2019-05-17 09:54发布

问题:

I want to Implement a validation in a jersey such that if I send a duplicate value of UserName or Email which already exists in DataBase then it should throw an Error saying UserName/Email already exists.

How can I acheive this?

I gone through this jersey documentation

https://jersey.java.net/documentation/latest/bean-validation.html

https://github.com/jersey/jersey/tree/2.6/examples/bean-validation-webapp/src

But I couldn't understood what exactly I have to follow to make my custom Jersey validations.

Suppose I send a Json in Body while Creating a User like:

 {  
     "name":"Krdd",
     "userName":"khnfknf",
     "password":"sfastet",
     "email":"xyz@gmail.com",
     "createdBy":"xyz",
     "modifiedBy":"xyz",
     "createdAt":"",
     "modifiedAt":"",

  }

Thanks in Advance for your helping hands.

回答1:

Assuming you have a request instance of class:

public class UserRequest {

    // --> NOTICE THE ANNOTATION HERE <--
    @UniqueEmail(message = "email already registered")
    private final String email;

    public UserRequest(String email) {
        this.email = email;
    }

    public String getEmail() {
        return email;
    }
}

You have to add a new annotation (and link it to your validator class using @Constraint):

@Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { UniqueEmailValidator.class })
@Documented
public @interface UniqueEmail {
    String message();

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };

}

then you also have to implement the validation itself:

public class UniqueEmailValidator implements ConstraintValidator<UniqueEmail, UserRequest> {
    @Override
    public void initialize(UniqueEmail constraintAnnotation) {

    }

    @Override
    public boolean isValid(UserRequest value, ConstraintValidatorContext context) {
        // call to the DB and verify that value.getEmail() is unique
        return false;
    }
}

and you're done. Remember that Jersey is using HK2 internally so binding some sort of a DAO to your Validator instance can be tricky if you use Spring or other DI.