@valid and @validation concepts and related use and Bindingresult bindingresult in the SPRINGMVC calibration framework

Source: Internet
Author: User

1. Compare

@Valid is used when using hibernate validation

@Validated is only used with the spring Validator check mechanism \

2. Implement

Among them, @valid, Java's jsr303 declares this kind of interface, hibernate-validator it implements

3. Reliance

The dependencies that need to be introduced when using MAVEN framework consolidation are as follows:

<span>        <dependency>              <groupId>javax.validation</groupId>              <artifactId> validation-api</artifactid>              <version>1.1.0.Final</version>          </dependency>              <dependency>              <groupId>org.hibernate</groupId>              <artifactid>hibernate-validator </artifactId>              <version>5.2.1.Final</version>          </dependency></span>

  

4.jsr303 the type of validation defined

Null check @null Verify that the object is null@notnull to verify that the object is not null, that a string of length 0 cannot be checked to check if the constraint string is Null or if the length of the trim is greater than 0, the string only, and the front and back spaces are removed. @No Tempty checks whether the constraint element is null or empty. Booelan checks @asserttrue to verify that the Boolean object is True @AssertFalse verifies that the Boolean object is a false length check @size (min=, max=) Validation object (Array, collection,map,string) length within a given range @Length (min=, max=) validates that the annotated String is between Min and Max include D. Date check @past Verify that the date and calendar objects are @Future before the current time to verify that the date and Calendar objects @Pattern validate the String after the current time It is recommended to use the Stirng,integer type, which is not recommended on the type of int, because the form value is "" cannot be converted to int, but can be converted to stirng to "", Integer is null@min to verify Num The BER and string objects are large equal to the specified value @Max verify that number and string objects are small equal to the specified value @DecimalMax the value being dimensioned 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 dimensioned 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 verifies that the composition of number and string is legitimate @Digits (integer=,fraction=) verifies that the string is compliant with the specified lattice Interger Specifies the integer precision, fraction specifies the decimal precision. @Range (min=, max=) ChEcks whether the annotated value lies between (inclusive) the specified minimum and maximum. @Range (min=10000,max=50000,mes Sage= "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 to perform recursive validation) @CreditCardNumber credit card verification @email Verify that it is an e-mail address, and if it is null, validation is passed. @ScriptAssert (lang=, script=, alias=) @URL (protocol=,host=, port=,regexp=, flags=)

  

5. Use

To create a new class

/** * * @Title: Appconfiglist.java * @Package Com.bonree.browser.model * @Description: White list url matching rule class * @author Phycho * @da  Te 2017/6/26 pm 4:45:30 * @version V1.0 */public class Appconfiglist extends page<appconfiglist> {private Integer Id;//id @NotNull (message = "AppId cannot be empty", groups = {AccountGroup.Update.class}) private Integer appid;//app Id @Not Empty (message = "rule cannot be empty", groups = {Appconfiggroup.add.class,appconfiggroup.update.class}) @Size (max = 200,groups= {App Configgroup.add.class,appconfiggroup.update.class}) Private String url;//URL rule @NotNull (message = "Typec cannot be empty", Grou PS = {AccountGroup.Update.class}) private Byte Typec = 1;//type private date createtime;//creation time private date modif    time;//Update Time @NotNull (message = "Status parameter cannot be null", groups = {AppConfigGroup.Update.class}) private Byte status = 1;//State Private Double orders;//Field order/** * Generate GET, set method * * @return */public String GetUrl () {RET    Urn URL; } publicInteger getId () {return id;    } public void SetId (Integer id) {this.id = ID;    } public Integer Getappid () {return appId;    } public void Setappid (Integer appId) {this.appid = AppId;    } public Byte Gettypec () {return typec;    } public void Settypec (Byte typec) {this.typec = Typec;    Public Date Getcreatetime () {return createtime;    } public void Setcreatetime (Date createtime) {this.createtime = Createtime;    Public Date Getmodiftime () {return modiftime;    } public void Setmodiftime (Date modiftime) {this.modiftime = Modiftime;    } public Byte GetStatus () {return status;    } public void SetStatus (Byte status) {this.status = status;    } public Double getorders () {return orders;    } public void Setorders (Double orders) {this.orders = orders;    } public void SetUrl (String url) {this.url = URL; }}

  

Checksum logic

/**     * @param result binding Results     * @param model data Models     * @return Whether an error occurred (true: An error occurred, false: no error occurred)     * @Description: Backstage School Verify     *    /public static Boolean validate (Bindingresult result, model model) {        Boolean validateresult = false;        if (Result.haserrors ()) {            Validateresult = true;            if (model = null) {                Fielderror error = result.getfielderrors (). get (0);//To avoid a large number of checks in front of the stack, affecting the user experience, only return an error message                Log.debug ("Validate error:" + error.getdefaultmessage ());                Model.addattribute ("msg", Error.getdefaultmessage ());            }        }        return validateresult;    }

  

Use in a controller

Add Whitelist Rule    @RequestMapping (value = "/page/add", method = Requestmethod.post)    @ResponseBody public    Resultdata Addurlrule (@Validated (AppConfigGroup.Add.class) appconfiglist appconfiglist, bindingresult result, Model Model) {        //background check        if (validatehandler.validate (result, model)) {            return null;        }        Appconfiglist.setstatus ((byte) 1);        Appconfiglist.setcreatetime (New Date ());        Appconfiglist.setmodiftime (New Date ());        Double orders = Appconfigservice.selectordersbyappid (Appconfiglist.getappid ());        if (orders = = null) {            appconfiglist.setorders (double) +);        } else {            appconfiglist.setorders (orders + );        }        Return GetResult (Appconfigservice.insert (appconfiglist));    }

  

6. Supplement

APR 8, 2:13:57 PM org.apache.catalina.core.StandardWrapperValve invoke SEVERE:Servlet.service () for Servlet SPRINGM      VC threw exception Javax.validation.UnexpectedTypeException:No validator could be found for Type:java.lang.Integer At Org.hibernate.validator.engine.ConstraintTree.verifyResolveWasUnique (constrainttree.java:383) at Org.hibernate.validator.engine.ConstraintTree.findMatchingValidatorClass (constrainttree.java:364) at Org.hibernate.validator.engine.ConstraintTree.getInitializedValidator (constrainttree.java:313) at Org.hibernate.validator.engine.ConstraintTree.validateConstraints (constrainttree.java:144) at Org.hibernate.validator.engine.ConstraintTree.validateComposingConstraints (constrainttree.java:233) at Org.hibernate.validator.engine.ConstraintTree.validateConstraints (constrainttree.java:128) at Org.hibernate.validator.engine.ConstraintTree.validateConstraints (constrainttree.java:117) at Org.hibernate.validator.metadata.MetAconstraint.validateconstraint (metaconstraint.java:84) at Org.hibernate.validator.engine.ValidatorImpl.validateConstraint (validatorimpl.java:452)

  

Be careful when using Hibernate validator in the event of an error

Difference between @NotNull and @NotEmpty and @notblank

@NotEmpty used above the collection class
@NotBlank used on string
@NotNull used on the base type

If you use Notempty or Notblank on the base type, you'll get the error above.

@valid and @validation concepts and related use and Bindingresult bindingresult in the SPRINGMVC calibration framework

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.