目录
1. Validator使用概述
通常来说一个api开放的参数都需要做验证,在开发期间也遇到一些问题,所以以下作出一些总结分享。
常用的单数据源源码可以参考:springboot-jpa-demo(spring-hibernate-validator)
以下源码会放在spring-jpa-multiple-datasources分支。
数据库使用的是postgres。
2. Validator使用案例
2.1 数据库准备
1) 当前db是public,有一张userinfo表。
2) public.userinfo数据。
2.2 核心代码
1) 实体类。
@Data
public class UserInfoDTO {
@NotBlank(message = "name can not null")
@Length(max = 20, message = "name can not exceed 20 characters")
@Pattern(regexp = "^[\\u4E00-\\u9FA5A-Za-z0-9\\*]*$", message = "no more than 10 characters,including text, letters, and numbers.")
@JsonProperty(value = "name")
private String name;
@NotBlank(message = "gender can not null")
@JsonProperty(value = "gender")
private String gender;
@NotNull(message = "age can not empty")
@Min(value = 1, message = "age should be between 1 and 120")
@Max(value = 120, message = "age should be between 1 and 120")
@JsonProperty(value = "age")
private int age;
@NotNull(message = "futureDate can not empty")
@Future(message = "futureDate is invalid")
@JsonProperty(value = "futureDate")
private Date futureDate;
@NotNull(message = "birthDate can not empty")
@Past(message = "birthDate is invalid")
@JsonProperty(value = "birthDate")
private Date birthDate;
}
注:如果需要对字段进行验证却不生效,加上@NotNull。
2) 全局异常处理器。
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* After the parameter verification fails, MethodArgumentNotValidException will be thrown.
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
StringJoiner sj = new StringJoiner(";");
e.getBindingResult().getFieldErrors() // get all the errors
.forEach(x -> sj.add(x.getDefaultMessage()));
Map map = new HashMap<>();
map.put("code", UUID.randomUUID());
map.put("msg", sj.toString());
return map;
}
/**
* After the parameter verification fails, ConstraintViolationException will be thrown.
*/
@ExceptionHandler(ConstraintViolationException.class)
public Map handleConstraintViolationException(ConstraintViolationException e) {
StringJoiner sj = new StringJoiner(";");
e.getConstraintViolations().forEach(x -> sj.add(x.getMessage()));
Map map = new HashMap<>();
map.put("code", 1001);
map.put("msg", sj.toString());
return map;
}
}
2.3 案例测试
如果已经安装了postman可以直接用:
{
"name": "123123",
"age": 1,
"gender": "female",
"birthDate": "2000-04-23",
"futureDate": "2022-05-23"
}
或者用:postman脚本
1) 正常通过验证。
更新后的userInfo表。
2) 验证失败。
附:
1) 如果需要验证的属性带有嵌套层级,可以将@Valid用在嵌套层级的成员属性上。