JAVA Validation background parameter Validation

Source: Internet
Author: User

First, preface

In the background development process, the validation of parameters becomes an indispensable part of the development environment. For example, the parameter can not be null,email so must conform to the format of email, if manually make if judgment or write regular expression to judge the unintended development efficiency is too slow, in time, cost, quality of the game will inevitably lag behind. So the verification layer is the inevitable result of abstraction, the following is a few solutions.

Second, the solution

  1, struts2 valid can be configured Xml,xml describes the rules and the returned information, this way is more cumbersome, low development efficiency, not recommended

2, validation bean is based on the JSR-303 standard developed, using annotated way to achieve, and convenient, the following will focus on

3, Hibernate Validator. This is a hibernate-independent package that can be referenced directly, and is actually extended on the basis of the validation bean, as

    

   4, Oval is an extensible Java Object Data Validation framework, the validation rules can be set by configuration files, Annotation, POJOs. Rules can be written using pure Java language, JavaScript, Groovy, BeanShell, etc.

Iii. Introduction to Bean Validation Framework validation

  The bean validation package is maintained on MAVEN and the latest package coordinates are as follows:

<dependency>    <groupId>javax.validation</groupId>    <artifactid>validation-api </artifactId>    <version>1.1.0.Final</version></dependency>

Latest Address: http://search.maven.org/#search%7cgav%7c1%7cg%3a%22javax.validation%22%20and%20a%3a%22validation-api%22

After the download to open this package, there is a packages called constraints, which is put in the verification of the annotations:

   Let's start with code practice:

1, define a bean:Student.java to be verified

1  PackageCom.use;2 3 Importjavax.validation.constraints.*;4 Importjava.io.Serializable;5 ImportJava.math.BigDecimal;6 Importjava.util.Date;7 8  Public classStudentImplementsSerializable {9 Ten  One@NotNull (message = "Name cannot be empty") A     PrivateString name; -  -@Size (min = 6,max = 30,message = "Address should be between 6-30 characters") the     PrivateString address; -  -@DecimalMax (value = "100.00", message = "a little overweight.") -@DecimalMin (value = "60.00", message = "have some more rice.") +     PrivateBigDecimal weight; -  +     PrivateString Friendname; A @AssertTrue at     PrivateBoolean ishavefriend () { -         returnFriendname! =NULL?true:false; -     } -  -@Future (message = "Birthday must precede current practice") -     PrivateDate birthday; in  -@Pattern (regexp = "^ (. +) @ (. +) $", message = "The format of the mailbox is not valid") to     PrivateString Email; +  -  the      PublicString GetName () { *         returnname; $     }Panax Notoginseng  -      Public voidsetName (String name) { the          This. Name =name; +     } A  the      PublicString getaddress () { +         returnaddress; -     } $  $      Public voidsetaddress (String address) { -          This. Address =address; -     } the  -      PublicBigDecimal getweight () {Wuyi         returnweight; the     } -  Wu      Public voidsetweight (BigDecimal weight) { -          This. Weight =weight; About     } $  -      PublicString Getfriendname () { -         returnFriendname; -     } A  +      Public voidsetfriendname (String friendname) { the          This. Friendname =Friendname; -     } $  the      PublicDate Getbirthday () { the         returnbirthday; the     } the  -      Public voidsetbirthday (Date birthday) { in          This. Birthday =birthday; the     } the  About      PublicString Getemail () { the         returnemail; the     } the  +      Public voidsetemail (String email) { -          This. email =email; the     }Bayi}
View Code

2. Test class: Studenttest.java

1  PackageCom.use;2 3 Importjavax.validation.ConstraintViolation;4 Importjavax.validation.Validation;5 ImportJavax.validation.Validator;6 Importjavax.validation.ValidatorFactory;7 Importjava.io.Serializable;8 ImportJava.math.BigDecimal;9 Importjava.util.ArrayList;Ten Importjava.util.Date; One Importjava.util.List; A ImportJava.util.Set; -  -  Public classStudenttestImplementsSerializable { the      Public Static voidMain (string[] args) { -Student xiaoming =Getbean (); -List<string> Validate =Validate (xiaoming); -Validate.foreach (Row, { + System.out.println (row.tostring ()); -         }); +  A     } at  -     Private StaticStudent Getbean () { -Student Bean =NewStudent (); -Bean.setname (NULL); -Bean.setaddress ("Beijing")); -Bean.setbirthday (NewDate ()); inBean.setfriendname (NULL); -Bean.setweight (NewBigDecimal (30)); toBean.setemail ("xiaogangfan163.com"); +         returnBean; -     } the  *     Private StaticValidatorfactory factory =validation.builddefaultvalidatorfactory (); $ Panax Notoginseng      Public Static<T> list<string>Validate (T t) { -Validator Validator =factory.getvalidator (); theSet<constraintviolation<t>> constraintviolations =validator.validate (t); +  AList<string> messagelist =NewArraylist<>(); the          for(constraintviolation<t>constraintviolation:constraintviolations) { + Messagelist.add (Constraintviolation.getmessage ()); -         } $         returnmessagelist; $     } -}
View Code

3. Summary

    • Like @notnull, @Size, and so simple and easy to understand, not much to say
    • @Pattern because this is a regular, so can do more things, such as Chinese or digital, mailbox, length, etc. can be done
    • @AssertTRue This is fundamentally different from other validation annotations because it is associated with another field. example, the Ishavefriend method relies on the Friendname field check
    • The validated API is processed by me so that you can return the information in bulk
    • The framework is still relatively simple, and sometimes the annotations we need may not be available, so we need to customize the annotations and byte-write implementations. The next section will discuss hibernate validation,

JAVA Validation background parameter Validation

Related Article

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.