註解 | 做用類型 | 解釋 |
---|---|---|
@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("參數驗證經過"); }