If yous endeavour to annotated your edible bean plain with @Email, nada volition conduct house :-)
I'll simply write the virtually of import business office of the code, together with therefore I assume yous already bring a javaee6 spider web projection created. I advise yous create that past times using jboss javaee6 archetype.
For event nosotros desire a custom e-mail validator, nosotros volition ask at to the lowest degree four classes: bean, entity, @interface together with the validator implementation. So let's get-go amongst the entity class, let's say nosotros bring a User:
@Entity @Table world shape User implements Serializeable { @Email someone String email; }As yous tin see, nosotros annotated the e-mail plain amongst @Email annotation. After that let's define the Email annotation:
import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Documented @Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) world @interface Email { String message() default "message.validation.invalidEmail"; Class[] groups() default {}; Class[] payload() default {}; String regexp() default "([^.@]+)(\\.[^.@]+)*@([^.@]+\\.)+([^.@]+)"; }This object contains the variables needed past times a ConstraintValidator such equally message, group, etc. And move the implementation class:
import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; world shape EmailValidator implements ConstraintValidator<Email, String> { @Override world void initialize(Email constraintAnnotation) { } @Override world boolean isValid(String value, ConstraintValidatorContext context) { endeavour { novel InternetAddress(value).validate(); } choose grip of (AddressException e) { provide false; } provide true; } }This shape validates if a given value is e-mail using the InternetAddress class. The EmailValidator implements ConstraintValidator amongst type parameters <interface, value>.
Note that yous tin initialize plain inward initialize() method, together with therefore after yous tin role these fields inward isValid().
And that's it nosotros straightaway bring a custom e-mail validator. Just a reminder, inward unopen to of the shape similar the ones defined inward hibernate yous volition honour that the interface contains: @Constraint(validatedBy = { }), simply withdraw these property. This holding specify which validator to use, without value it volition non validate. Or yous tin specify the validator amongst this property: @Constraint(validatedBy = { EmailValidator.class })
0 komentar:
Please comment if there are any that need to be asked.