Using Spring's validator interface for validation

Source: Internet
Author: User
Tags compact

You can use the validator interface provided by spring to verify the object. Validatorinterface and Errors work together, when spring checks, it aggregates all the checksum errors into the Errors object.

To see this simple data object:

 Packagecontainer.test; Public classPerson {PrivateString name; Private intAge ;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }}

To implement the org.springframework.validation.Validator two methods in the interface, we will Person add a checksum behavior to the class:

    • supports(Class): Indicates Validator if this is supported Class by this instance?

    • validate(Object, org.springframework.validation.Errors): Validates the supplied object and registers the officer error with the incoming Errors object.

Implementing one Validator is also relatively straightforward, especially if you have learned what Spring has to offer ValidationUtils . Let's take a look at how you can create a validator.

 Packagecontainer.test;Importorg.springframework.validation.Errors;Importorg.springframework.validation.ValidationUtils;ImportOrg.springframework.validation.Validator;/*** Data Validation for Spring Framework *@authorAdministrator **/ Public classPersonvalidatorImplementsValidator { Public Booleansupports (Class clazz) {returnPerson.class. Equals (Clazz); }     Public voidValidate (Object obj, Errors e) {validationutils.rejectifempty (E,"Name", "Name.empty"); Person P=(person) obj; if(P.getage () <0) {E.rejectvalue ("Age", "Negativevalue"); }Else if(P.getage () >110) {E.rejectvalue ("Age", "Too.darn.old"); }    }}

As you can see, we use one of the ValidationUtils 静态 methods in rejectIfEmpty(..) verifying the Name property, and if the ‘name‘ property is null either an empty string, the validation is rejected. Please refer to the relevant Javadoc for a look at some of the ValidationUtils features other than those described in the example.

For complex objects, it is certainly possible to implement Validator classes to validate their built-in property classes, but it Validator might be a better idea to implement a sample implementation for each built-in class. An example of such a ' rich ' is the Customer class, which contains two String attributes (first name and second name), and a complex Address object. Addressobjects may be independent of the Customer object, thus implementing one independently AddressValidator . If you want your CustomerValidator AddressValidator internal logic to be reused, but you don't want to do it by copying and pasting, you can either rely on the CustomerValidator injected object in your AddressValidator or create one. Then use this:

 Public classCustomervalidatorImplementsValidator {Private FinalValidator Addressvalidator;  Publiccustomervalidator (Validator addressvalidator) {if(Addressvalidator = =NULL) {          Throw NewIllegalArgumentException ("The supplied [Validator] is required and must isn't be null.")); }      if(!addressvalidator.supports (Address.class)) {          Throw NewIllegalArgumentException ("The supplied [Validator] must support the validation of [Address] instances."); }       This. Addressvalidator =Addressvalidator; }    /*** This Validator validates customer instances, and any subclasses of customer too*/    Public Booleansupports (Class clazz) {returnCustomer.class. IsAssignableFrom (Clazz); }    Public voidValidate (Object target, Errors Errors) {validationutils.rejectifemptyorwhitespace (Errors,"FirstName", "field.required"); Validationutils.rejectifemptyorwhitespace (Errors,"Surname", "field.required"); Customer Customer=(Customer) target; Try{Errors.pushnestedpath ("Address"); Validationutils.invokevalidator ( This. Addressvalidator, Customer.getaddress (), errors); } finally{Errors.popnestedpath (); }   }}

Validation errors are reported to the incoming Errors object. In spring Web MVC, you can use <spring:bind/> tags to check for error messages, but you can also handle errors on your own. The description of the method it provides can be found in its javadoc.

Using Spring's validator interface for 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.