Data validation Framework Apache BVal Introduction

Source: Internet
Author: User

Apache BVal (source code) is the reference implementation of the Entity data validation Java Bean Validation. Apache BVal provides the implementation of all the built-in constraint in the JSR 303 specification for constraining the definition, description, and validation of the values of fields in the Bean. If the JSR specification slag may not be clear, but did POJO hibernate Validator annotations Friends know is what,-then why not use the mainstream hibernate Validator? Because a simple compression package is already 13MB (although there can be documents, the source of the other), BVal only 400 KB, and I only need to service-side verification,-the innocent child paper can not hurt AH. My ORM is Mybatis, too.

Spring MVC 3.x, though it comes with the authenticator validatior, can validate the data submitted by the form in the controller, but this validator is extremely weak, because you need to encode the IF (null) Else warn ("Cannot empty data") completely manually,-- Too perverted (into the example below)--we need a framework to reduce time-consuming labor, and this kind of validation framework emerges.

    Import org.springframework.validation.Errors;      Import Org.springframework.validation.ValidationUtils;      Import Org.springframework.validation.Validator;             public class Uservalidator implements Validator {public                 Boolean supports (class<?> clazz) {             //TODO Auto-ge nerated method Stub             return User.class.equals (clazz);          }                 public void Validate (Object obj, Errors Errors) {             //TODO auto-generated method stub             Validationutils.rejectifempty (Errors, "username", NULL, "username is empty.");             User user = (user) obj;             if (null = = User.getpassword () | | ". Equals (User.getpassword ()))                 Errors.rejectvalue (" password ", NULL," Password is empty. ");}               

And that's what we'd ideally like to say in POJO. Statement of validation conditions:

Import Javax.validation.constraints.Min;  Import Javax.validation.constraints.NotNull;  Import Org.hibernate.validator.constraints.NotBlank;     public class User {      private String username;        private String password;      private int age;         @NotBlank (message= "User name cannot be empty") public      String GetUserName () {         return username;      }      public void Setusername (String username) {         this.username = username;      }      @NotNull (message= "password cannot be null") public      String GetPassword () {         return password;      }      public void SetPassword (String password) {         this.password = password;      }         @Min (value=10, message= "min.") Public      int Getage () {         return age;      }      public void Setage (int.) {         this.age = age;      }  }  

How do you do it with Apache BVal? We are still inseparable from Spring, in the MVC XML configuration file, add the following:

<mvc:annotation-driven validator= "Validator"/><!--data validation Validator bean--><bean id= "validator" class= " Org.springframework.validation.beanvalidation.LocalValidatorFactoryBean ">    <property name=" Providerclass "value=" Org.apache.bval.jsr.ApacheValidationProvider "/></bean><!--//-

Inject Bval verifier, and also let MVC turn on annotation drivers. With <mvn:annotation-driven/>, Spring automatically detects the JSR-303 provider under CLASSPATH and automatically enables support for JSR-303.

By the way, package dependencies are like this.


You can then add annotations to the POJO and declare the bean's validation in the controller, as in the following example @Valid T news, otherwise Bval will not work.

/** * NEW  * @return * * * @RequestMapping (method = requestmethod.post) public String Create (@Valid T news,  Bindingresult Result,model Model) {System.out.println ("new"), if (Result.haserrors ()) {Logger.info ("Create error!");} Else{logger.info ("Create ok!");} News.setservice (GetService ()); try {getService (). Create (news); Model.addattribute ("Newlyid", News.getid ());} catch ( Serviceexception e) {model.addattribute ("ErrMsg", e.tostring ());} return "Common/entity/json_cud";}

It is important to note that the parameter order of the Controller method. The Binding Result must be behind the Bean. This is the convention of Spring MVC. MVC has nothing to do with the order of the other parameters of the controller, except for this bindingresult. The goal is to allow multiple beans to be allowed, so there are multiple bindingresult.

How to deal with the error is not detailed said, different scenarios under different requirements.

Can I customize the validation criteria? I haven't tried it, so I should be able to refer to Hibernate Validator's practice. The following article is very detailed.

"Use of SPRINGMVC validator verification"

Data validation Framework Apache BVal Introduction

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.