Java back-end checksum-using Hibernate-validator checksum JavaBean

Source: Internet
Author: User
Tags jboss

Only the front-end check and its insecurity, the validation of the specification are both front and back of the form check, the following describes the use of hibernate-validator for back-end verification.

1. Add Dependent dependencies

 <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.1.Final</version> </dependency> <!--https:// mvnrepository.com/artifact/javax.validation/validation-api--  <dependency> <groupId>javax.validation</groupId> <artifactid        >validation-api</artifactId> <version>1.0.0.GA</version> </dependency> <!--https:// mvnrepository.com/artifact/ Org.jboss.logging/jboss-logging-->  <dependency> <groupid>org.jboss.logging</gr Oupid> <artifactId>jboss-logging</artifactId> <version>3.1.0.cr2</version>        ; </dependency> 

2. Define a public validation class

ImportJava.util.HashMap;ImportJava.util.Iterator;ImportJava.util.Map;ImportJava.util.Set;Importjavax.validation.ConstraintViolation;Importjavax.validation.Validation;ImportJavax.validation.Validator;ImportOrg.hibernate.validator.HibernateValidator;/** *  * @authorLeave **/ Public classValidationutils {/*** Use hibernate annotations for verification **/    Private StaticValidator Validator =Validation. Byprovider (hibernatevalidator.class). Configure (). FailFast (true). Buildvalidatorfactory (). Getvalidator (); /*** * * Task: *@paramobj *@return* date:2018 Year July 5 *@authorPengluo **/     Public Static<T> map<string,object>Validate (T obj) {stringbuffer buffer=NewStringBuffer ();//used to store the error message after validationmap<string,object> map =NewHashmap<string, object>(); Set<ConstraintViolation<T>> constraintviolations =validator.validate (obj); //throw a Test exception        if(Constraintviolations.size () > 0) {Iterator<ConstraintViolation<T>> iter =Constraintviolations.iterator ();  while(Iter.hasnext ()) {String message=Iter.next (). GetMessage ();               Buffer.append (message); } map.put ("IsValid",false); Map.put ("MSG", buffer.tostring ()); returnmap; }        Else{map.put ("IsValid",true); returnmap; }    }}

3. Define validation rules using annotations in JavaBean

    @NotEmpty (message= "name cannot be empty! ")    private  String name;     = "\\d{3,4}-\\d{7,8} (-\\d{3,4})?", message = "Phone number format error"    )Private  String Tel    ; = "1[3|4|5|6|7|8| 9]\\D{9} ", message =" Phone number format is wrong! ")    private  String moble;     = "([a-za-z0-9_-]) [email protected] ([a-za-z0-9_-]) + (. [ A-za-z0-9_-] + ", message =" Bad mailbox format! ")    private String email;

4. Check the JavaBean, through the Validationutils verification results, you can know in detail which field validation failed, the results back to the front-end interaction.

        ...//check before persisting in a controller or service
map<string,object> ValMap = validationutils.validate (addressbook); // package return parameters, such as Status,msg,code, etc. New Alijson (); if ((Boolean) valmap.get ("IsValid")) { = Addressbookservices.saveaddressbook (addtxlutils ( Request, AddressBook)); } Else { json.getjsonfalse (JSON, Valmap.get ("MSG"). toString ()); }
......

Common annotations Everyone can own Baidu, thank you, I am very vegetable, do not accept criticism, ha haha.

Java back-end checksum-using Hibernate-validator checksum JavaBean

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.