SpringBoot (sixteen) validator background verification

validator background verification

In Spring Boot, Validator can be used to verify the validity of form data and other input data. Here are the steps to use Validator:

1. Notes

Generally speaking, when the front end submits data to the back end, certain verification will be performed, such as using jqueryvalidatejs or the vue-validator in the currently left Vue framework for verification. But there are certain risks in this way, so we will verify the data format in the background. Some validation annotations are provided in Java or Hibernate. This section learns to use the background validation data format. First, let's look at the annotations of the background verification for our use, which are explained as follows.

@Valid: The annotated element is an object, and all field values ​​​​of this object need to be checked.

@Null: The annotated element must be null.

@NotNull: The annotated element must not be null

@AssertTrue: The annotated element must be true

@AssertFalse: The annotated element must be false

@Min(value): The annotated element must be a number whose value must be greater than or equal to the specified minimum value.

@Max(value): The annotated element must be a number whose value must be less than or equal to the specified maximum value.

@DecimalMin(value): The annotated element must be a number whose value must be greater than or equal to the specified minimum value.

@DecimalMax(value): The annotated element must be a number whose value must be less than or equal to the specified maximum value.

@Size(maxmin): The size of the annotated element must be within the specified range.

@Digits(integer, fraction): The annotated element must be a number whose value must be within an acceptable range.

@Past: The annotated element must be a past date.

@Future: The annotated element must be a future date.

@Pattern(value): The annotated element must conform to the specified regular expression.

@Email: The annotated element must be an email address.

@Length(min=max=): The size of the annotated string must be within the specified range.

@NotEmpty: The annotated string must be non-empty.

@Range(min=max=): The annotated element must be within the appropriate range.

@NotBlank: The annotated string must be non-empty.

@URL(protocol=,host=port=regexp=flags=): The annotated string must be a valid URL.

@CreditCardNumber: The annotated string must pass the Luhn verification algorithm. Bank card, credit card and other numbers generally use Luhn to calculate the validity.

@ScriptAssert(lang=script=alias=): There must be a Java Scripting API, which is the implementation of JSR223 ("Scripting for the JavaTMPlatform").

@SafeHtml(whitelistType=additionalTags=): There must be a jsoup package in the classpath.

The differences between @NotNull, @NotEmpty, and @NotBlank are as follows.

@NotNull: The value of any object cannot be null.

@NotEmpty: The element of the collection object is not 0, that is, the collection is not empty, and it can also be used for strings that are not null List item​

@NotBlank: It can only be used when the string is not null, and the length of the string trim) must be greater than 0.

2. Integration steps

1. Import dependencies

<!--validator后台校验-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

2. Entity class annotations

@Data
public class Person {
  @NotNull //该属性不能为空
   private String name;
   @NumberFormat //要符合数值类型
   private Integer age;
   @Email //被注解的元素必须是电子邮箱地址格式。
   private String email;
}

3. Use of controller parameters

Create a TestController for testing. Use the getAllErrors() method of the BindingResult class to obtain a set of prompts that do not meet the verification requirements. How to display them can be determined according to the project situation. Here, the error information is spliced ​​into a string and returned to the foreground:

@PostMapping("/validator")
//@Valid:被注解的元素是一个对象,需要检查此对象的所有字段值。
//BindingResult:使用BindingResult类的getAllErrors()方法可以获取不符合校验的提示集合,
// 具体怎么展示可以根据项目情况决定,这里是将错误信息拼接成字符串返回前台:
public StringBuffer postTest2(@RequestBody @Valid Person person, BindingResult bindingResult){
    StringBuffer stringBuffer= new StringBuffer();
    if(bindingResult.hasErrors()){
        List<ObjectError> list = bindingResult.getAllErrors();//不符合校验的提示集合
        list.forEach(error->{
            stringBuffer.append(error.getDefaultMessage());//不符合校验的信息,append:字符串拼接
            stringBuffer.append(" || ");
            System.out.println(error.getDefaultMessage());
        });
    }
    System.out.println("postTest2");
    return stringBuffer;//这里是将错误信息拼接成字符串返回前台
}

4. Test

Guess you like

Origin blog.csdn.net/m0_65992672/article/details/130450687