java – 如何在Jersey中使用自定义验证
发布时间:2020-12-15 04:46:40 所属栏目:Java 来源:网络整理
导读:我想在泽西中实现验证,这样如果我发送一个已存在于DataBase中的UserName或Email的重复值,那么它应该抛出一个错误,说UserName / Email已经存在. 我该如何实现这一目标? 我浏览了这个球衣文件 https://jersey.java.net/documentation/latest/bean-validation.
我想在泽西中实现验证,这样如果我发送一个已存在于DataBase中的UserName或Email的重复值,那么它应该抛出一个错误,说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":"",} 在此先感谢您的帮助. 解决方法
假设您有一个类的请求实例:
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将其链接到您的验证器类): @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实例可能会很棘手. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |