java - How do I use Custom Validations in Jersey -


i want implement validation in jersey such if send duplicate value of username or email exists in database should throw error saying username/email exists.

how can acheive this?

i gone through jersey documentation

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

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

but couldn't understood have follow make custom jersey validations.

suppose send json in body while creating user like:

 {        "name":"krdd",      "username":"khnfknf",      "password":"sfastet",      "email":"xyz@gmail.com",      "createdby":"xyz",      "modifiedby":"xyz",      "createdat":"",      "modifiedat":"",    } 

thanks in advance helping hands.

assuming have request instance of class:

public class userrequest {      // --> notice annotation here <--     @uniqueemail(message = "email registered")     private final string email;      public userrequest(string email) {         this.email = email;     }      public string getemail() {         return email;     } } 

you have add new annotation (and link 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 have implement validation itself:

public class uniqueemailvalidator implements constraintvalidator<uniqueemail, userrequest> {     @override     public void initialize(uniqueemail constraintannotation) {      }      @override     public boolean isvalid(userrequest value, constraintvalidatorcontext context) {         // call db , verify value.getemail() unique         return false;     } } 

and you're done. remember jersey using hk2 internally binding sort of dao validator instance can tricky if use spring or other di.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -