我如何在 Jersey 中使用自定义验证

How do I use Custom Validations in Jersey

我想在球衣中实施验证,如果我发送重复的用户名或电子邮件值,而该值已经存在于数据库中,那么它应该抛出一个错误,提示 UserName/Email 已经存在。

我怎样才能做到这一点?

我浏览了这件球衣文档

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

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

但我不明白我必须遵循什么才能进行自定义 Jersey 验证。

假设我在创建用户时在 Body 中发送了一个 Json,例如:

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

  }

在此先感谢您的帮助。

假设您有一个 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;
    }
}

您必须使用@Constraint 添加一个新注释(并且 link 它到您的验证器 class):

@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 { };

}

那么你还必须自己实现验证:

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;
    }
}

大功告成。请记住,Jersey 在内部使用 HK2,因此如果您使用 Spring 或其他 DI,将某种 DAO 绑定到您的 Validator 实例可能会很棘手。