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

标签 java spring validation rest jersey

我想在 Jersey 中实现验证,这样如果我发送重复的 UserName 或 Email 值,而该值已经存在于数据库中,那么它应该抛出一个错误,指出 UserName/Email 已经存在。

我怎样才能做到这一点?

我浏览了这个 Jersey 文档

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":"",

  }

在此先感谢您的帮助。

最佳答案

假设你有一个类的请求实例:

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 将其链接到您的 validator 类):

@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 绑定(bind)到您的 validator 实例可能会很棘手。

关于java - 我如何在 Jersey 中使用自定义验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32304481/

相关文章:

java - JPA CriteriaBuilder 获取具有条件的列表实体

java - 从 Java 类调用时,Kotlin 数据类复制函数不起作用

java - Spring 批处理 : Execution order for multiple JobExecutionListener instances for a single job

java - 尝试在 java 中使用 TLSv2 连接到 ssl url 时出现错误 "handshake_failure"

java - Spring 安全: j_spring_security_check page not found

c# - 英孚。在没有 [Required] 属性的情况下引发字符串字段的必需验证错误

java - Apache Netbeans 10 CVS 插件不可用?

java - 如何在 PropertySource 中使用相对于用户家的路径

c# - 在 ASP.NET MVC3 中验证表单时,有什么方法可以忽略某些属性(在 POCO 上)?

jquery - 如何动态添加和删除要由 Parsley.js 验证的表单字段?