pom文件添加依赖
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.17.Final</version>
</dependency>
1. 创建实体类并且添加非空注解
在此说明 lombook的 @Data 有bug,有的时候会出现无法获取到值,值为null的情况,最好使用set,get 方法和tostring 重写
@Slf4j
@Data
public class Test {
@NotEmpty(message = "名称不能为空!")
private String name;
@NotEmpty(message = "性别不能为空!")
private String sex;
@NotEmpty(message = "地址不能为空!")
private String address;
@NotNull(message = "年龄不能为空!")
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public static Logger getLog() {
return log;
}
@Override
public String toString() {
return "test{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
", age=" + age +
'}';
}
}
控制器
在方法的参数中需要使用注解 @Valid 与实体类中的为空注解结合使用
@Slf4j
@RestController
@RequestMapping("/api/test")
public class TestController {
@PostMapping("/add")
public void add(@RequestBody @Valid Test test){
log.info("====新增的数据===="+test);
}
}
测试,这里使用的测试工具是RunAPI
通过JSON传参
正常返回结果
{
"name":"测试",
"age":"22",
"address":"444444",
"sex":"男"
}
缺少age传值
{
"name":"测试",
"address":"444444",
"sex":"男"
}
返回结果
{6 items
"timestamp":"2022-04-01T03:28:45.102+0000"
"status":400
"error":"Bad Request"
"errors":[1 item
0:{8 items
"codes":[...]4 items
"arguments":[...]1 item
"defaultMessage":"年龄不能为空!"
"objectName":"test"
"field":"age"
"rejectedValue":NULL
"bindingFailure":false
"code":"NotNull"
}
]
"message":"Validation failed for object='test'. Error count: 1"
"path":"/api/test/add"
}
|