Java – how to use custom validation in Jersey
I want to implement verification in Jersey, so if I send a duplicate value of username or email that already exists in the database, it should throw an error saying that username / email already exists
How can I achieve this goal?
I browsed the Jersey file
https://jersey.java.net/documentation/latest/bean-validation.html
https://github.com/jersey/jersey/tree/2.6/examples/bean-validation-webapp/src
But I can't understand what I have to follow to perform custom Jersey validation
Suppose I send JSON in the body when creating a user, such as:
{
"name":"Krdd","userName":"khnfknf","password":"sfastet","email":"xyz@gmail.com","createdBy":"xyz","modifiedBy":"xyz","createdAt":"","modifiedAt":"",}
Thank you for your help
Solution
Suppose you have a request instance of a 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 must add a new comment (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 must also 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;
}
}
When you're done, remember that Jersey uses hK2 internally, so binding a Dao to a validator instance can be tricky if you use spring or other di
