注解 | 做用类型 | 解释 |
---|---|---|
@NotNull | 任何类型 | 属性不能为null |
@NotEmpty | 集合 | 集合不能为null,且size大于0 |
@NotBlanck | 字符串、字符 | 字符类不能为null,且去掉空格以后长度大于0 |
@AssertTrue | Boolean、boolean | 布尔属性必须是true |
@Min | 数字类型(原子和包装) | 限定数字的最小值(整型) |
@Max | 同@Min | 限定数字的最大值(整型) |
@DecimalMin | 同@Min | 限定数字的最小值(字符串,能够是小数) |
@DecimalMax | 同@Min | 限定数字的最大值(字符串,能够是小数) |
@Range | 数字类型(原子和包装) | 限定数字范围(长整型) |
@Length | 字符串 | 限定字符串长度 |
@Size | 集合 | 限定集合大小 |
@Past | 时间、日期 | 必须是一个过去的时间或日期 |
@Future | 时期、时间 | 必须是一个将来的时间或日期 |
字符串 | 必须是一个邮箱格式 | |
@Pattern | 字符串、字符 | 正则匹配字符串 |
// 咱们能够直接拷贝系统内的注解如@Min,复制到咱们新的注解中,而后根据须要修改。 @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER}) @Retention(RUNTIME) @Documented //注解的实现类。 @Constraint(validatedBy = {IsMobileValidator.class}) public @interface IsMobile { //校验错误的默认信息 String message() default "手机号码格式有问题"; //是否强制校验 boolean isRequired() default false; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
咱们知道注解只是一个标记,真正的逻辑还要在特定的类中实现,上一步的注解指定了实现校验功能的类为IsMobileValidator。java
// 自定义注解必定要实现ConstraintValidator接口奥,里面的两个参数 // 第一个为 具体要校验的注解 // 第二个为 校验的参数类型 public class IsMobileValidator implements ConstraintValidator<IsMobile, String> { private boolean required = false; private static final Pattern mobile_pattern = Pattern.compile("1\\d{10}"); //工具方法,判断是不是手机号 public static boolean isMobile(String src) { if (StringUtils.isEmpty(src)) { return false; } Matcher m = mobile_pattern.matcher(src); return m.matches(); } @Override public void initialize(IsMobile constraintAnnotation) { required = constraintAnnotation.isRequired(); } @Override public boolean isValid(String phone, ConstraintValidatorContext constraintValidatorContext) { //是否为手机号的实现 if (required) { return isMobile(phone); } else { if (StringUtils.isEmpty(phone)) { return true; } else { return isMobile(phone); } } } }
@Data public class User { @NotNull @Size(min=2, max=30,message = "请检查名字的长度是否有问题") private String name; @NotNull @Min(18) private Integer age; //这里是新添加的注解奥 @IsMobile private String phone; }
而后在controller的每一个接口中使用@Validated和BindingResult类app
@Validated注解用于验证一个入参,验证以后的消息绑定到BindingResult类中:ide
@PostMapping("/test") @ApiOperation(value = "测试", notes = "", response = Result.class) public Result test(@ApiParam(name = "test", value = "参数", required = true) @Validated @RequestBody Test test, BindingResult bindingResult) { if(bindingResult.hasErrors()){ String errorMsg = bindingResult.getFieldError().getDefaultMessage(); return Result.error(errorMsg); } return Result.ok("参数验证经过"); }