Development tools: STS code download Link: https://github.com/theIndoorTrain/Springboot/tree/1ef5e597a6f866e73387c0238dbcdf46cfcf39b9 preface:
When we submit the form, how to quickly filter the form, Springboot provides us with the annotation method of the validation rules.
Below, let's simply use form validation.
First, simple example: 1. Build the project:
2. Add Pojo Entity User:
1 PackageCom.xm.pojo;2 3 Importjavax.validation.constraints.Min;4 5 ImportOrg.hibernate.validator.constraints.NotBlank;6 7 Public classUser {8@Min (value=10,message= "ID cannot be less than 10")9 Private intID;Ten@NotBlank (message= "name cannot be empty") One PrivateString name; A Public intgetId () { - returnID; - } the Public voidSetId (intID) { - This. ID =ID; - } - PublicString GetName () { + returnname; - } + Public voidsetName (String name) { A This. Name =name; at } - @Override - PublicString toString () { - return"User [id=" + ID + ", name=" + name + "]"; - } - in -}
User.java
3. Add Controller:
1 PackageCom.xm.controller;2 3 Importjava.util.List;4 5 ImportJavax.validation.Valid;6 7 ImportOrg.springframework.validation.BindingResult;8 ImportOrg.springframework.validation.FieldError;9 Importorg.springframework.web.bind.annotation.PostMapping;Ten Importorg.springframework.web.bind.annotation.RequestMapping; One ImportOrg.springframework.web.bind.annotation.RestController; A - ImportCom.xm.pojo.User; - the @RestController - Public classUsercontroller { - -@RequestMapping ("/hello") + PublicString Hello () { - return"Hello Spring boot!"; + } A at@PostMapping ("/user") - PublicString addUser (@Valid User user,bindingresult result) { - if(Result.haserrors ()) { - -List<fielderror> fielderrors =result.getfielderrors (); - for(Fielderror error:fielderrors) { in System.out.println (Error.getdefaultmessage ()); - } to returnfielderrors.tostring (); + } - returnuser.tostring (); the } * $}
Usercontroller.java
4. Test:
Second, check the annotations
@Min |
Value= number, which represents the minimum value of the validation attribute |
@Max |
Value= number, which represents the maximum value of the validation attribute |
@NotBlank |
The string cannot be empty and cannot be empty, with the length of the string removed The length of the tail |
@NotEmpty |
The object cannot be empty, and the size>0 |
@NotNull |
Object cannot be empty, |
@Email |
string as Mailbox format |
2018-06-23
1, springboot------form validation