16. Spring boot parameter verification

Time:2022-5-14

1、 Summary

Validation is mainly used to verify the validity of the data submitted by the user, such as whether it is empty, whether the password conforms to the rules, whether the email format is correct, etc. there are many verification frameworks, most of which are hibernate validator. It also supports internationalization and can customize the annotation of verification types
Official documents

2、 Basic use

import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.*;
@Data
public class UserQuery {
    private Long id;
    @NotBlank
    @Length(min = 6, max = 15)
    private String username;
    @NotBlank
    @Email
    private String email;
    @NotBlank
    @Pattern (regexp = "^ (1 [3-9] [0-9]) \ \ d{8} $", message = "incorrect phone number format")
    private String phone;
    @Min(value = 1)
    @Max(value = 100)
    private int age;
    @NotBlank
    @Length (min = 6, max = 12, message = "nickname length is 6 to 12 bits")
    private String nickname;
}
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
public class AccountController {
    @PostMapping("/users")
    public String register(@Valid @RequestBody UserQuery user, BindingResult result) {
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            String field = fieldError.getField();
            String msg = fieldError.getDefaultMessage();
            return field + ":" + msg;
        }
        return "success";
    }
}

3、 Common verification

1、JSR-330

Validator built-in annotation

annotation detailed information
@Null The annotated element must benull
@NotNull The annotated element must not be emptynull
@AssertTrue The annotated element must betrue
@AssertFalse The annotated element must befalse
@Min(value) The annotated element must be a number and its value must be greater than or equal to the specified minimum value
@Max(value) The annotated element must be a number and its value must be less than or equal to the specified maximum value
@DecimalMin(value) The annotated element must be a number and its value must be greater than or equal to the specified minimum value
@DecimalMax(value) The annotated element must be a number and its value must be less than or equal to the specified maximum value
@Size(max, min) The size of the annotated element must be within the specified range
@Digits (integer, fraction) The annotated element must be a number and its 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

2. Constraint attached to hibernate validator

annotation detailed information
@Email The annotated element must be an email address
@Length The size of the annotated string must be within the specified range
@NotEmpty The of the annotated string must be non empty
@Range The annotated element must be within the appropriate range
@NotBlank The validation string is not null and the length must be greater than 0

be careful

  • @NotNullFor any type, annotated elements must not be associated with null
  • @NotEmptyApplicable to string map or array cannot be null and the length must be greater than 0
  • @NotBlankIt can only be used for string and cannot be null. After calling trim(), the length must be greater than 0

4、 Verification mode

1. Explain

  1. Normal mode (this mode is the default)
  2. Quick failure return mode

2. Normal mode

After verifying all properties, all verification failure information is returned. The default is normal mode without configuration

3. Quick return mode

As long as one verification fails, an error message is returned

@Configuration
public class ValidateConfig {
    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                .failFast(true)
                .buildValidatorFactory();
        return validatorFactory.getValidator();
    }
}

5、 Verification method

1. Explain

Common verification methods:

  1. Encapsulated into bean for verification
  2. Single parameter verification
  3. Group check
  4. Correlation check

2. Chestnuts

2.1. Request parameters are encapsulated into entity classes

@Data
@Validated
public class ProductQuery {
    @NotNull
    private String keyword;
    @Min (value = 0, message = "illegal parameter")
    private Long categoryId;
    private Integer page = 1;
    private Integer size = 10;
    private Integer sort = 0;
}
@RestController
public class ValidatedController {
    @GetMapping("/validated")
    public String validatedBean(@Valid  ProductQuery userVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            //Get error information directly
            List<String> errors = bindingResult.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
            //Get the attribute information of the parameter
            // List<String> errors = bindingResult.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.toList());
        }
        return "sucess";
    }
}

2.2. Method parameter verification

  1. Use the @ validated annotation on the class
  2. Just use the verification annotation on the parameter
@RestController
@Validated
public class ValidatedController {
    @GetMapping("/validated/params")
    public String validatedParams(@RequestParam @NotNull Long id, BindingResult bindingResult) {
        return bindingResult.hasErrors() ? "success" : "error";
    }
}

2.3. Correlation verification

The check object contains another check object

@Data
@Validated
public class ProductQuery {
    @NotNull
    private String keyword;
    @Min (value = 0, message = "illegal parameter")
    private Long categoryId;
    private Integer page = 1;
    private Integer size = 10;
    private Integer sort = 0;
    @Valid
    BrandQuery brandQuery;
}
@Data
public class BrandQuery {
    @NotBlank
    private String brandName;
}
@GetMapping("/validated/association")
public String validatedAssociation(@Validated ProductQuery userVo, BindingResult bindingResult) {
  return bindingResult.hasErrors() ? "success" : "error";
}

2.4 group verification

In actual development, we often encounter this situation: we want to use one entity class to receive multiple objectscontrollerBut the parameters required by different controllers are slightly different.

When verifying the grouping order, verify according to the specified grouping order. If the previous verification fails, the subsequent groups will not be verified.

6、 Check error handling

1. Explain

  1. ConstraintViolationException
  2. MethodArgumentNotValidException
  3. BindException

2. Chestnuts

2.1 method parameter verification processing

If the verification fails, an error message will be thrownConstraintViolationExceptionThen we catch this exception in the global exception capture class and return a unified result set

@GetMapping("/validated/constraint")public ResponseResult<String> validatedError(@RequestParam @NotNull Long id) {  return ResponseResult.success("success");}
@ [email protected] Class globalexceptionhandler {/ * * * constraintviolationexception * single parameter violation constraint check exception * / @ exceptionhandler (constraintviolationexception. Class) public responseresult < string > handleconstraintviolationexception (constraintviolationexception E) {log.error (e.getmessage(), e); return responseresult. Error();}}

2.2. Request parameter form object

@ [email protected] Class productquery {@ notnull private string productid; @ notnull private string keyword; @ min (value = 0, message = "illegal parameter") private long categoryid; private integer page = 1; private integer size = 10; private integer sort = 0; @ valid brandquery brandquery;}
@PostMapping("/validate/method")public User methodArgs(@Valid @RequestBody ProductQuery productQuery){    return user;}

2.3 common objects

If @ requestbody is not used, bindexception exception will be thrown

@PostMapping("/validate/method")public ResponseResult<String> methodArgs(@Valid ProductQuery productQuery){    return ResponseResult.success("success");}

7、 Custom verification

1. Explain

  1. Create constraint annotation class
  2. Create validator

2. Create annotation class

@Target({ElementType.PARAMETER, ElementType.FIELD})@ [email protected] (retentionpolicy. Runtime) @ constraint (validatedby = customordervalidator. Class) public @ interface customorder {string values(); string message() default "must be a specified field"; class <? > [] groups() default {}; Class<?  extends Payload>[] payload() default {};}

3. Create verification class

/*** custom sorting field verification rules * / public class customordervalidator implements constraintvalidator < customorder, string > {private string values; @ override public void initialize (customorder constraintanannotation) {this. Values = constraintanannotation. Values();} / * ** Otherwise, the verification fails. * *@ Param value the value entered by the user, For example, a value * / @ override public Boolean isvalid (string value, constraintvalidatorcontext, constraintvalidatorcontext) {string [] args = values. Split (","); if (args. Length > 0) {for (string Val: args) {if (val.equals (value)) {return true;}}} return false;    }}

4. Use

@GetMapping("/search")public ResponseResult<String> search(@CustomOrder(values = "1,2,3,4") Integer sort) {  return ResponseResult.success("success");}