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