先列一下常用的Validation注解
注解 | 作用 |
---|---|
@NotNull | 值不能为空 |
@Null | 值必须为空 |
@Pattern(regex=) | 字符串必须匹配正则表达式 |
@Size(min, max) | 集合或者数组元素的数量必须在min和max之间 |
@CreditCardNumber(ignoreNonDigitCharacters=) | 字符串必须是信用卡号,按找美国的标准验证 |
字符串必须是Email地址 | |
@Length(min, max) | 检查字符串的长度 |
@NotBlank | 字符串不能为空串 |
@NotEmpty | 字符串不能为null, 集合或者数组的 size 不能为空 |
@Range(min, max) | 数字必须大于min, 小于max |
@SafeHtml | 字符串必须是安全的html |
@URL | 字符串必须是合法的URL |
@AssertFalse | 值必须是false |
@AssertTrue | 值必须是true |
@DecimalMax(value=, inclusive=) | 值必须小于等于(inclusive=true)/小于(inclusive=false)属性指定的值,也可以注释在字符串类型的属性上。 |
@DecimalMin(value=, inclusive=) | 值必须大于等于(inclusive=true)/小于(inclusive=false)属性指定的值,也可以注释在字符串类型的属性上。 |
@Digist(integer=,fraction=) | 数字格式检查。integer指定整数部分的最大长度,fraction指定小数部分的最大长度 |
@Future | 时间必须是未来的 |
@Past | 事件必须是过去的 |
@Max(value=) | 值必须小于等于value指定的值。不能注解在字符串类型属性上。 |
@Min(value=) | 值必须小于等于value指定的值。不能注解在字符串类型属性上。 |
最常用的方式只要在需要校验的变量前加@Valid 然后在变量的属性上加上各种需要的注解就可以了
如:
@PostMapping
Mono<Result<AccountDTO>> create(@RequestBody @Valid AddAccountDTO addAccountDTO) {
/**
* 租户ID
*/
@NotBlank
private String tenantId;
/**
* 账户名称
*/
@NotBlank
private String accountName;
/**
* 认证账户名
*/
private String authAccountName;
/**
* 昵称
*/
@NotBlank
private String nickname;
如果是单个的参数,比如是一个 PathVariable 就可以把注解验证的注解直接加到参数的前边。
@GetMapping(value = "/bind/email/{accountId}")
Mono<Result<String>> bindEmailRequest(@PathVariable Long accountId, @NotBlank String newEmail) {
这里会有一个小问题,当参数不合法的时候,控制台会打印错误,而且返回结果的说明也不太好看。
这时候就需要增加自动定义的异常处理。
/**
* @Author: tiantao
* @Date: 2020/9/9 10:28 AM
* @Version 1.0
*/
@Component
public class GlobalErrorAttributes extends DefaultErrorAttributes {
public GlobalErrorAttributes() {
super(false);
}
@Override
public Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
return assembleError(request);
}
参考文章:https://blog.csdn.net/u012373815/article/details/72049796