SpringBoot series (5): The data check web project

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/mu_wind/article/details/99672581

Data verification of the web project

Data validation

In web development, data validation is very important to make sure that the front end of the back-end program must pass or the parameters of the data obtained from the semantic layer is speaking right through rigorous verification.
JSR is a specification document that specifies a set of API, by adding constraints to label the object properties. Hibernate Validator is embodied and JSR specification, Hibernate Validator provides all the constraints built achieve JSR specification annotations, annotation and some additional constraints, in addition to the user can also customize the constraints comments.
Use Hibernate Validator check data, you need to define a data model received, using annotations in the form of description field validation rules, we have to Student object demonstrates how to use an example for everyone.

First, WebController add a saved method saveStudent, parameters for the Student.

@RequestMapping("/saveStudent")
public void saveUser(@Valid Student student,BindingResult result) {
    System.out.println("student:" + student);
    if(result.hasErrors()) {
        List<ObjectError> list = result.getAllErrors();
        for (ObjectError error : list) {
            System.out.println(error.getCode()+ "-" + error.getDefaultMessage());
        }
    }
}
  1. Add annotations @Valid front @Valid parameters representative of the object using the calibration parameters;
  2. BindingResult parameter check results are stored in this object, by checking whether the can, not by checking the error message may be printed according to the attribute determination.

Next, in the User to add parameters to be verified annotations corresponding, different attributes, in accordance with the rules of the content to add different checksum.

public class Student {
    @NotEmpty(message="姓名不能为空")
    private String name;
    @Max(value = 100, message = "年龄不能大于100岁")
    @Min(value= 18 ,message= "必须年满18岁!" )
    private int age;
    @NotEmpty(message="密码不能为空")
    @Length(min=6,message="密码长度不能小于6位")
    private String password;
    //...
}

Where, message = "password can not be blank" error message is returned by the custom.
Use MockMvc conduct a test:

@Test
public void saveStudents() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.post("/saveStudent")
            .param("name","")
            .param("age","101")
            .param("password","test")
    );
}

The results returned:

user:name=,age=666,pass=test
Max-年龄不能大于100
Length-密码长度不能小于6
NotEmpty-姓名不能为空

The results showed that all validation rules has been triggered, it returns an error message, the error message may be encapsulated in the actual use, and returns to the front-end display.
Common check:

annotation application Check Item
@Length(min=, max=) String Check if the string length according range
@Max(value=) In numeric or string type represents a number Check whether the value is less than or equal to the maximum
@Min(value=) In numeric or string type represents a number Check whether the value is greater than or equal to the minimum
@NotNull Attributes Check that the value is not empty (not null)
@Past date or calendar Check whether the date is past time
@Future date or calendar Check if the date is future tense
@Pattern(regex=“regexp”, flag=) String Check whether the property is given regular expression matching flag match
@Range(min=, max=) String to numeric or digital type to represent a Checking whether a value between the minimum and maximum values ​​(including threshold)
@Size(min=, max=) array,collection,map Check whether the element size between the minimum and maximum values ​​(including threshold)
@AssertFalse Attributes The method of calculation result of the checking of whether to false (for code-represented annotations and not restrictive manner useful)
@AssertTrue Attributes Check whether the method of calculation results to true (for code-represented annotations and not restrictive manner useful)
@Valid Property (object) Recursive associated object for verification. If the object is a collection or array, recursively verify its elements; if the object is the Map, verify the value of the element recursively
@Email String Check whether the string line with a valid email address specification

Guess you like

Origin blog.csdn.net/mu_wind/article/details/99672581