spring-boot 2.X 使用验证框架

1,556 阅读1分钟

Springn boot 支持JSR-303,Bean验证框架

参数自动校验

pom.xml

        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.3.0.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
    

接收类

public class Person {

    @NotBlank(message = "name not null")
    @Length(min = 2, max = 10,message = "name length between 2 and 10")
    private String name;

    @DecimalMin(value = "10", message = "age must be greater than 10")
    private int age;

    @Email(message = "email")
    private String email;
    
    ....
    getter/setter

}

Controller 类

@RestController
@Validated // 类上使用 @Validated 注解
public class ValidatedTest {

    // 参数上使用 @Valid 才能验证 List
    @RequestMapping("/validated")
    public void test01(@RequestBody @Valid List<Person> list) {
        System.out.println(list);
    }

}

参数检验异常处理

@RestControllerAdvice
public class WebExceptionHandler {

    /**
     * 参数校验异常类
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public Map<String, Object> handlerConstraintViolationException(ConstraintViolationException exception) {
        Map<String, Object> result = new HashMap<>();
        Set<ConstraintViolation<?>> constraintViolations = exception.getConstraintViolations();
        StringBuilder strBuilder = new StringBuilder();
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            String message = constraintViolation.getMessage();
            strBuilder.append(message).append(" ; ");
        }
        result.put("msg", strBuilder.toString());
        result.put("code", -1);
        return result;
    }
}

验证规则

JSR-303

  • 空检查

    • @Null 验证对象是否为空
    • @NotNull 验证对象不为空
    • @NotBlank 验证字符串不为空或者不是空字符串 trim()
    • @NotEmpty 验证对象不为null,或者集合不为空
  • 长度检查

    • @Size(min=,max=) 验证对象长度,可支持字符串、集合
    • @Length 字符串大小
  • 数组检测

    • @Min 验证数字是否大于等于指定的值
    • @Max 验证数字是否小于等于指定的值
    • @Digits 验证数字是否符合指定格式,如@Digits (integer=9,fraction=2)
    • @Range 验证数字是否在指定的范围内,如@Range(min=1,max=1000)
  • 其他

    • @Email 验证是否为邮件格式,为null则不作校验
    • @Pattern 验证String 对象是否符合正则表达式的规则