SpringBoot2.0之四 @Validated注解校验

在Spring Boot中,@Validated注解用于验证请求参数。它可以应用在Controller类或方法上;
@Validated注解应用在Controller类上,方法参数的注解@NotBlank(message = “xx不能为空”)才会生效;
@Validated注解应用在方法上,方法的参数对象中的属性的@NotBlank、@NotNull注解才会生效,要想在参数的属性和参数上都使用校验注解,类和方法的参数前都得加@Validated注解。

1、引入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

2、参数说明与使用示例
注解验证的数据类型描述
@NotNull任意类型验证属性不能为null
@NotBlank字符串验证字符串属性不能为空且长度必须大于0
@Size(min,max )CharSequence
Collection
Map
Array
字符串:字符串长度必须在指定的范围内
Collection:集合大小必须在指定的范围内
Map:map的大小必须在指定的范围内
Array:数组长度必须在指定的范围内
@Min整型类型验证数字属性的最小值
@Max整型类型验证数字属性的最大值
@DecimalMin数字类型验证数字属性的最小值(包括小数)
@DecimalMax数字类型验证数字属性的最大值(包括小数)
@Digits(integer,fraction)数字类型验证数字属性的整数位数和小数位数
@Email字符串类型验证字符串属性是否符合Email格式
@Pattern字符串验证字符串属性是否符合指定的正则表达式
@Positive数字类型验证数值为正数
@PositiveOrZero数字类型验证数值为正数或0
@Negative数字类型验证数值为负数
@NegativeOrZero数字类型验证数值为负数或0
@AssertTrue布尔类型参数值必须为 true
@AssertFalse布尔类型参数值必须为 false
@Past时间类型(Date)参数值为时间,且必须小于 当前时间
@PastOrPresent时间类型(Date)参数值为时间,且必须小于或等于 当前时间
@Future时间类型(Date)参数值为时间,且必须大于 当前时间
@FutureOrPresent时间类型(Date)参数值为时间,且必须大于或等于 当前日期

校验代码示例:

@Data
public class User {
    // @NotNull:验证属性不能为null。
    @NotNull(message = "用户名不能为null")
    private String username;

    // @NotBlank:验证字符串属性不能为空且长度必须大于0。
    @NotBlank(message = "用户名不能为空且长度必须大于0")
    private String username1;

    // @Size:验证字符串属性的长度范围。
    @Size(min = 6, max = 20,message = "密码最小6位,最长20位")
    private String password;

    // @Min:验证数字属性的最小值。
    @Min(value = 18,message = "年龄最小18岁")
    private int age;

    // @Max:验证数字属性的最大值。
    @Max(100)
    private int age1;

    // @DecimalMin:验证数字属性的最小值(包括小数)。
    @DecimalMin("0.01")
    private BigDecimal price;

    // @DecimalMax:验证数字属性的最大值(包括小数)。
    @DecimalMax("1000.00")
    private BigDecimal price1;

    // @Digits:验证数字属性的整数位数和小数位数。
    @Digits(integer = 3, fraction = 2)
    private BigDecimal weight;

    // @Email:验证字符串属性是否符合Email格式。
    @Email
    private String email;

    // @Pattern:验证字符串属性是否符合指定的正则表达式。
    @Pattern(regexp = "[A-Za-z0-9]+")
    private String username2;
    
    // @Positive:验证数值为正数
    @Positive
    private int age2;

    // @PositiveOrZero:验证数值为正数或0
    @PositiveOrZero
    private int age3;

    // @Negative:验证数值为负数
    @Negative
    private int age4;

    // @NegativeOrZero:验证数值为负数或0
    @NegativeOrZero
    private int age5;

    // @AssertTrue:参数值必须为 true
    @AssertTrue
    private boolean hasMoney;

    // @AssertFalse:参数值必须为 false
    @AssertFalse
    private boolean hasMoney1;

    // @Past:参数值为时间,且必须小于 当前时间
    @Past
    private Date time;

    // @PastOrPresent:参数值为时间,且必须小于或等于 当前时间
    @PastOrPresent
    private Date time1;

    // @Future:参数值为时间,且必须大于 当前时间
    @Future
    private Date time2;

    // @FutureOrPresent:参数值为时间,且必须大于或等于 当前日期
    @FutureOrPresent
    private Date time3;
}

嵌套校验:

在被检验的字段上添加 @Valid 注解就可以实现嵌套检验

@Data
public class User3 {
    @Valid
    List<User2> user2List;

    @Valid
    private User2 user2;
}

@Data
 class User2 {
    @NotBlank(message = "用户名不能为空!")
    private String username;
}

3、校验注解的三个参数:

在这里插入图片描述

  • message:自定义错误消息。可以通过该参数指定验证失败时返回的错误消息。
    示例:
public class User {
    @NotBlank(message = "用户名不能为空")
    private String username;
    
    // getter and setter
}

  • groups:分组校验。可以通过该参数指定在特定的验证分组中才进行验证。
    示例:
public interface Group1 {}

public interface Group2 {}

public class User {
    @NotBlank(groups = Group1.class)
    private String username;
    
    @NotBlank(groups = Group2.class)
    private String password;
    
    // getter and setter
}

username属性只在Group1分组中进行验证,password属性只在Group2分组中进行验证。

  • payload:用于携带额外的验证信息。可以通过该参数传递一些自定义的验证信息。(不常用)
    示例:
public class User {
    @NotBlank(payload = {ValidationInfo.class})
    private String username;
    
    // getter and setter
}

public class ValidationInfo {
    private String info;
    
    // getter and setter
}

当验证失败时,可以通过ConstraintViolation对象获取到ValidationInfo对象,并获取其中的验证信息。

Set<ConstraintViolation<User>> violations = validator.validate(user);
for (ConstraintViolation<User> violation : violations) {
    if (violation.getConstraintDescriptor().getPayload().contains(ValidationInfo.class)) {
        ValidationInfo validationInfo = violation.getConstraintDescriptor().getPayload(ValidationInfo.class);
        String info = validationInfo.getInfo();
        // 处理验证信息
    }
}

4、在post 和 get 请求上使用

在post上使用@Validated,get上直接放校验注解

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值