This demo is mainly to let Spring's @validated annotations and hibernate support the JSR data validation of some of the annotations together to complete the data validation. This demo is used by Springboot.
First the code for the domain object Foo is as follows:
Package Com.entity;import Org.hibernate.validator.constraints.email;import Org.hibernate.validator.constraints.notblank;import javax.validation.constraints.Min; Public classFoo {@NotBlank (message="This name cannot be empty") PrivateString name; @Min (Value= -, message ="This age is the smallest") PrivateInteger age; @Email (Message="Bad mailbox Format") PrivateString Email; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicInteger getage () {returnAge ; } Public voidsetage (Integer age) { This. Age =Age ; } PublicString Getemail () {returnemail; } Public voidsetemail (String email) { This. email =email; }}
Next the controller layer code is as follows:
Package Com.validation;import Com.entity.bar;import com.entity.barvalidator;import com.entity.foo;import Org.springframework.validation.bindingresult;import Org.springframework.validation.objecterror;import Org.springframework.validation.annotation.validated;import Org.springframework.web.bind.webdatabinder;import Org.springframework.web.bind.annotation.initbinder;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.restcontroller;import Javax.validation.valid;import java.util.List;@ Restcontroller Public classFoocontroller {@RequestMapping ("/footest") PublicString foo (@Valid foo foo, bindingresult result) {if(Result.haserrors ()) {List<ObjectError> allerrors =result.getallerrors (); for(Objecterror objecterror:allerrors) {String defaultmessage=Objecterror.getdefaultmessage (); System. out. println ("defalutmessage="+defaultmessage); } System. out. println ("allerrors="+Allerrors.toarray ()); return "failed"; } return "Success"; } }
The code to start spring boot is as follows:
Package Com.validation;import Org.springframework.boot.springapplication;import Org.springframework.boot.autoconfigure.springbootapplication;import Org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, @SpringBootApplication (exclude={ Datasourceautoconfiguration. class })publicclass application { publicstaticvoid Main (string[] args) { springapplication.run (application. class , args);} }
Perform data validation in the background with some annotations of spring @validated annotations and org.hibernate.validator.constraints.*