@Valid注解相关使用

@Valid注解相关

  • 依赖

  • <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    ​<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
    
    ​
    ​
    <!--或者  ------- -->
    ​
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
     
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.4.1.Final</version>
    </dependency>

验证注解验证的数据类型说明
@Valid任何非原子类型指定递归验证关联的对象如用户对象中有个地址对象属性,如果想在验证用户对象时一起验证地址对象的话,在地址对象上加@Valid注解即可级联验证
@AssertFalseBoolean,boolean验证注解的元素值是false
@AssertTrueBoolean,boolean验证注解的元素值是true
@Null任意类型验证注解的元素值是null
@NotNull任意类型验证注解的元素值不是null
@NotEmptyCharSequence子类型、Collection、Map、数组验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)
@NotBlankCharSequence子类型验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的首位空格
@Length(min=下限, max=上限)CharSequence子类型验证注解的元素值长度在min和max区间内
@Size(min=下限, max=上限)字符串、Collection、Map、数组等验证注解的元素值的在min和max(包含)指定区间之内,如字符长度、集合大小
@Range(min=最小值, max=最大值)BigDecimal,BigInteger,CharSequence, byte, short, int, long等原子类型和包装类型验证注解的元素值在最小值和最大值之间
@Min(value=值)BigDecimal,BigInteger, byte,short, int, long,等任何Number或CharSequence(存储的是数字)子类型验证注解的元素值大于等于@Min指定的value值
@Max(value=值)和@Min要求一样验证注解的元素值小于等于@Max指定的value值
@DecimalMin(value=值)和@Min要求一样验证注解的元素值大于等于@ DecimalMin指定的value值
@DecimalMax(value=值)和@Min要求一样验证注解的元素值小于等于@ DecimalMax指定的value值
@Digits(integer=整数位数, fraction=小数位数)和@Min要求一样验证注解的元素值的整数位数和小数位数上限
@Pastjava.util.Date,java.util.Calendar;Joda Time类库的日期类型验证注解的元素值(日期类型)比当前时间早
@PastOrPresent与@Past要求一样验证注解的元素值(日期类型)是当前时间或者比当前时间早
@Future与@Past要求一样验证注解的元素值(日期类型)比当前时间晚
@FutureOrPresent与@Past要求一样验证注解的元素值(日期类型)是当前时间或者比当前时间晚
@Email(regexp=正则表达式,flag=标志的模式)CharSequence子类型(如String)验证注解的元素值是Email,也可以通过regexp和flag指定自定义的email格式
@Pattern(regexp=正则表达式,flag=标志的模式)String,任何CharSequence的子类型验证注解的元素值与指定的正则表达式匹配

@NouNull、@NotEmpty、@NotBlank

@NotEmpty注解的String、Collection、Map、数组不能为null或者长度为0的(纯空格的String符合规则)

@NotBlank注释的String不能为null或空的 (尾部空格被忽略,纯空格的String也是不符合规则。即trim()之后,要length>0才符合)

@NotNull 注释的元素不能为null,但可以为empty,没有长度的约束。接受任何类型

String str = null; //都不能为null
@NotNull: false
@NotEmpty: false
@NotBlank: false
 
String str = "";
@NotNull: true    //可以为空 没有长度限制
@NotEmpty: false
@NotBlank: false
 
String str = " ";
@NotNull: true
@NotEmpty: true  //长度为1 不除去空格
@NotBlank: false //用trim()后 长度为0
 
String str = "Hello!";
@NotNull: true
@NotEmpty: true
@NotBlank: true

使用案例

@RequestMapping("/test")
@RestController
// 和get请求一起使用
@Validated
public class DemoController {
    

    @RequestMapping("test2")
    public String test2(@Valid @RequestBody Test2DTO param) {
        System.out.println(param);
        return "success";
    }

    @RequestMapping("test3")
    public Integer test3(@RequestParam @Min(value = 1L) Integer id) {
        return id;
    }

    @RequestMapping("test4/{id}")
    public Integer test4(@PathVariable("id") @Min(value = 1L) Integer id){
        return id;
    }
}


@Data
@AllArgsConstructor
@NoArgsConstructor
public class Test2DTO {
    @NotNull
    @Min(value = 1L,message = "Error_id")
    private Integer id;
    @NotNull
    @Length(max = 5,message = "ErrorUsername")
    private String username;
}

// 对于格式校验抛出的异常做处理(无需求可以不使用)
@RestControllerAdvice
public class ValidExceptionAdvice {


    private Resp<?> response(int errorCode, Exception e) {
        return new Resp<>(errorCode, e.getClass().getSimpleName() + "/" + e.getMessage());
    }

    /**
     * 处理@PathVariable和@RequestParam使用注解抛出的异常
     */
    @ExceptionHandler(value = {ValidationException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Resp<?> validationException(Exception e) {
        return response(1, e);
    }

    /**
     * 处理 @RequestBody 格式校验的异常
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.PRECONDITION_FAILED)
    public Resp<?> methodArgumentNotValidException(MethodArgumentNotValidException e) {

        String message = e.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(";"));
        return new Resp<>(3, message);
    }
}



@Data
public class Resp<T> {
    public static final Resp<Void> VOID = new Resp();

    public int code = 0;

    public String message;

    public T data;

    public Resp() {
    }

    public Resp(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public Resp(T data) {
        this.data = data;
    }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值