Java Spring Validator

Source: Internet
Author: User

1. Validation using Spring ' s Validator interface

Spring features a Validator interface that's can use to validate objects. the Validator interface works using a Errors object so it while validating, validators can report valid ation failures to the Errors object.

2. Data object:

public class Kmailpostform {    private Integer kid;    Public Kmailpostform () {    } public    Integer Getkid () {        return kid;    }    public void Setkid (Integer kid) {        this.kid = Kid;    }}

3. Validator:

Import Com.maduar.springbootdemo.form.kmailpostform;import Org.springframework.validation.errors;import Org.springframework.validation.validationutils;import Org.springframework.validation.validator;public Class Kmailpostformvalidator implements Validator {    @Override public    Boolean supports (class<?> clazz) {        Return KmailPostForm.class.equals (Clazz);    }    @Override public    Void Validate (Object target, Errors Errors) {        validationutils.rejectifempty (Errors, "Kid", " Kid.empty ");        Kmailpostform kmailpostform = (kmailpostform) target;        if (kmailpostform.getkid () = = null) {            errors.rejectvalue ("Kid", "Kid is null");        } else if (kmailpostform.getkid (). Intvalue () < 0) {            errors.rejectvalue ("Kid", "Kid < 0");}}}    

  

4. Controller

@RestController @requestmapping (value = "/user") public class Usercontroller {    @InitBinder public    Void Initbinder (DataBinder databinder) {        databinder.setvalidator (new Kmailpostformvalidator ());    }    @PostMapping (value = "/hellopost/") public    httpentity<?> hellopost (@Valid @RequestBody kmailpostform Kmailpostform, bindingresult result) {        if (result.haserrors ()) {            return Responseentity.ok ("error");        }        Return Responseentity.ok ("OK");}    }

  

A:springboot version 1.5.9.RELEASE

B:https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#validation

Java Spring Validator

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.