Use JSR-303 for background data validation

Source: Internet
Author: User

First, use in the SRINGMVC

Using annotations

1. Jar to be used when preparing the calibration

VALIDATION-API-1.0.0.GA.JAR:JDK interface;

Hibernate-validator-4.2.0.final.jar is the realization of the above interface;

log4j, SLF4J, slf4j-log4j

2. Write the bean to be verified

@NotNull (message= "name cannot be empty") private String userName; @Max (value=120,message= "The oldest cannot be checked") private int age; @Email ( Message= "Mailbox format error") Private String email;

3. The method of school prescription

@RequestMapping ("/login") public    String testvalid (@Valid user user, bindingresult result) {        if ( Result.haserrors ()) {            list<objecterror> errorlist = result.getallerrors ();            for (Objecterror error:errorlist) {                System.out.println (error.getdefaultmessage ());            }        }                   return "Test";    }

Note: Here a @valid parameter must be next to a bindingresult parameter, otherwise spring throws an exception directly when the checksum fails.

Second, hard-coded implementation mode

Manual Check Implementation method:

 1 Import java.util.Iterator; 2 Import Java.util.Set; 3 4 Import Javax.validation.ConstraintViolation; 5 Import javax.validation.Validation; 6 7 Import Org.apache.commons.lang3.StringUtils; 8 9/**10 * JSR303 Check helper class One * @author yangzhilong12 *13 */14 public class Jsr303util {15 16/**17 * If NULL is returned  Indicates no error. * @param obj19 * @return20 */21 public static String check (Object obj) {if (null = = obj) {"The entry parameter Vo cannot be empty";}25 set<constraintviolation<object>> Validresult = Validation.builddefaultvalidatorfactory (). Getvalidator (). validate (obj); + if (null! = Validresult && Valid Result.size () > 0) {StringBuilder sb = new StringBuilder (); Lation<object>> iterator = Validresult.iterator (); Iterator.hasnext ();) {constraintviolation<object> constraintviolation = (constraintviolation<object>) IteraTor.next (); if (Stringutils.isnotblank (Constraintviolation.getmessage ())) {Sb.appe nd (Constraintviolation.getmessage ()). Append (","); "+" Else {sb.append (Constraintvio Lation.getpropertypath (). toString ()). Append ("illegal,"),}35}36 if (Sb.lastindexof (  ",") = = Sb.length ()-1) {PNs Sb.delete (sb.length ()-1, Sb.length ());}39 return Sb.tostring ();}41 return null;42}43 44}

Three, JSR303 definition of the Check type

Empty check

@Null verifies whether the object is Null

@NotNull Verify that the object is not null and cannot search for a string of length 0

@NotBlank checks if the constraint string is null and if the length of trim is greater than 0, only the string, and the front and back spaces are removed.

@NotEmpty checks whether the constraint element is null or empty.

Booelan Check

@AssertTrue verifies whether a Boolean object is True

@AssertFalse Verify that the Boolean object is False

Length Check

@Size (min=, max=) verifies that the length of the object (array,collection,map,string) is within a given range

@Length (min=, max=) validates, the annotated string is between Min and Max included.

Date Check

@Past Verify that date and Calendar objects are before the current time

@Future Verify that date and Calendar objects are after the current time

@Pattern to verify that a String object conforms to a regular expression rule

Numeric check, recommended for use in Stirng,integer type, is not recommended for type int, because the form value is "" cannot be converted to int, but can be converted to stirng to "" and integer is null

@Min Verify that number and String objects are large equal to the specified value

@Max Verify that number and String objects are small equals the specified value

@DecimalMax the value that is being labeled must not be greater than the maximum value specified in the constraint. The parameter of this constraint is a string representation of the maximum value defined by BigDecimal. Decimal Presence Precision

@DecimalMin the value to be labeled must be not less than the minimum specified in the constraint. The parameter of this constraint is a string representation of the minimum value defined by BigDecimal. Decimal Presence Precision

@Digits Verify that the composition of number and String is legal

@Digits (integer=,fraction=) verifies that the string is a number that conforms to the specified format, interger Specifies the integer precision, fraction specifies the decimal precision.

The @Range (min=, max=) checks whether the number is between Min and Max.

@Range (min=10000,max=50000,message= "Range.bean.wage")
Private BigDecimal wage;

The @Valid recursively verifies the associated object, and if the associated object is a collection or an array, the element is recursively checked, and if it is a map, the value part of it is verified. (whether recursive validation is performed)

@CreditCardNumber Credit Card Verification

@Email Verify that the e-mail address, if NULL, is not validated and is validated.

@ScriptAssert (lang=, script=, alias=)

@URL (protocol=,host=, port=,regexp=, flags=)

Four. Custom restriction types

We can define our own restriction types in addition to the types of restrictions that JSR-303 native supports. Define your own restriction type first we have to define an annotation of that type of restriction, and that annotation requires the use of a @constraint callout. Now suppose we need to define a restriction type that represents an amount, so we can define this:

Java code
  1. Import Java.lang.annotation.ElementType;
  2. Import java.lang.annotation.Retention;
  3. Import Java.lang.annotation.RetentionPolicy;
  4. Import Java.lang.annotation.Target;
  5. Import Javax.validation.Constraint;
  6. Import Javax.validation.Payload;
  7. Import Com.xxx.xxx.constraint.impl.MoneyValidator;
  8. @Target ({Elementtype.field, elementtype.method})
  9. @Retention (Retentionpolicy.runtime)
  10. @Constraint (Validatedby=moneyvalidator.class)
  11. Public @interface Money {
  12. String message () default "is not in amount form";
  13. Class<?>[] Groups () default {};
  14. class<? Extends payload>[] Payload () default {};
  15. }

We can see that in the code above we have defined a money annotation, and the annotations are annotated with @constraint annotations, and using the @constraint annotation callout indicates that we have defined an annotation for the restriction. The Validatedby property of the @Constraint annotation is used to specify which constraintvalidator the current constraint type we define needs to be verified. In the code above we specified the money restriction type of the check class is Moneyvalidator. It is also important to note that there are three properties that must be defined when we define our own restriction type annotations, as shown in the code above message , groups and the Payload property.

After defining the restriction type money, the next step is to define our restriction type check class Moneyvalidator. The restriction type check class must implement the interface Javax.validation.ConstraintValidator and implement its initialize and IsValid methods. Let's take a look at Moneyvalidator's code example:

Java code
  1. Import Java.util.regex.Pattern;
  2. Import Javax.validation.ConstraintValidator;
  3. Import Javax.validation.ConstraintValidatorContext;
  4. Import Com.xxx.xxx.constraint.Money;
  5. public class Moneyvalidator implements Constraintvalidator<money, double> {
  6. Private String Moneyreg = "^\\d+ (\\.\\d{1,2})? $";//Regular expression representing the amount
  7. Private Pattern Moneypattern = Pattern.compile (Moneyreg);
  8. public void Initialize (Money money) {
  9. TODO auto-generated Method Stub
  10. }
  11. public boolean isValid (Double value, Constraintvalidatorcontext arg1) {
  12. TODO auto-generated Method Stub
  13. if (value = = null)
  14. return true;
  15. Return Moneypattern.matcher (Value.tostring ()). matches ();
  16. }
  17. }

From the above code we can see that constraintvalidator is using generics. It altogether needs to specify two types, the first type is the parameter type of the corresponding initialize method, and the second type is the first parameter type of the corresponding IsValid method. From the above two methods we can see that the IsValid method is used for verifying the

Use JSR-303 for background data validation

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.