如何在Jersey中使用自定义验证 [英] How do I use Custom Validations in Jersey
问题描述
我想在泽西中实现验证,这样如果我发送一个已存在于DataBase中的UserName或Email的重复值,那么它应该抛出一个错误,说UserName / Email已经存在。
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?
我浏览了这个球衣文件
< a href =https://jersey.java.net/documentation/latest/bean-validation.html\"rel =nofollow> https://jersey.java.net/documentation/latest/bean-validation.html
https://github.com/jersey/jersey/tree/2.6/examples/bean-validation-webapp/src
但是我无法理解我必须遵循什么来制作我的自定义Jersey验证。
But I couldn't understood what exactly I have to follow to make my custom Jersey validations.
假设我在创建用户时发送了一个Json in Body:
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":"",
}
提前感谢您的帮助。
推荐答案
假设您有一个类的请求实例:
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;
}
}
你必须添加一个新的注释(并链接它)使用@Constraint到你的验证器类:
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;
}
}
你已经完成了。请记住,Jersey在内部使用HK2,因此如果使用Spring或其他DI,将某种DAO绑定到Validator实例可能会非常棘手。
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.
这篇关于如何在Jersey中使用自定义验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!