@NotNull,@NotBlank和 @NotEmpty使用

1.实体类

package com.example;


import org.hibernate.validator.constraints.NotBlank; 
import org.hibernate.validator.constraints.NotEmpty;

import javax.validation.constraints.NotNull;
import java.util.List;

/*
    @NotNull    验证对象是否不为null, 无法查检长度为0的字符串
    @NotBlank 检查约束 (字符串) 是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
    @NotEmpty 检查(集合)约束元素是否为NULL或者是EMPTY.
    ********上面导入的是两个包******
*/
public class Student {
    @NotNull(message = "用户ID不能为空")
    private Long userID;
    @NotEmpty(message = "地址不能为空")
    private List addressID;
    @NotBlank(message = "备注不能为空")
    private String comment;

    public Student() {
    }
    public Long getUserID() {
        return userID;
    }
    public void setUserID(Long userID) {
        this.userID = userID;
    }
    public List getAddressID() {
        return addressID;
    }
    public void setAddressID(List addressID) {
        this.addressID = addressID;
    }
    public String getComment() {
        return comment;
    }
    public void setComment(String comment) {
        this.comment = comment;
    }
    @Override
    public String toString() {
        return "Order{" +
                "userID=" + userID +
                ", addressID=" + addressID +
                ", comment='" + comment + '\'' +
                '}';
    }

}

 

2.Controller

    @RequestMapping("/create")
    @ResponseBody
    public String create(@RequestBody @Valid Student dto, BindingResult results) {
        if (results.hasErrors()) {
            return results.getFieldError().getDefaultMessage();
        }
        return dto.toString();
    }

3.postman测试

@NotNull,@NotBlank和 @NotEmpty使用_第1张图片

 

 json对象

{
"addressID":["address1","address2","address3"],
"comment":"备注...",
"userID":100
}

 

 总结:  1.注意注解引用的包不一样

   2. @NotEmpty 用在集合类上面
    @NotBlank 用在String上面
    @NotNull    用在基本类型上

 

 

 

 

 
  

转载于:https://www.cnblogs.com/coloz/p/10697427.html

你可能感兴趣的:(@NotNull,@NotBlank和 @NotEmpty使用)