@Valid註解效驗數據 @NotNull,@NotBlank自動判定空值

@Valid

用於驗證註解是否符合要求,直接加在變量user之前,在變量中添加驗證信息的要求,當不符合要求時就會在方法中返回message 的錯誤提示信息。

  1. @RestController
  2. @RequestMapping("/user")
  3. public class UserController {
  4. @PostMapping
  5. public User create (@Valid @RequestBody User user) {
  6. System.out.println(user.getId());
  7. System.out.println(user.getUsername());
  8. System.out.println(user.getPassword());
  9. user.setId("1");
  10. return user;
  11. }
  12. }

然後在 User 類中添加驗證信息的要求:

  1. public class User {
  2. private String id;
  3. @NotBlank(message = "密碼不能爲空")
  4. private String password;
  5. }

@NotBlank 註解所指的 password 字段,表示驗證密碼不能爲空,如果爲空的話,上面 Controller 中的 create 方法會將message 中的"密碼不能爲空"返回。

當然也可以添加其他驗證信息的要求:

限制 說明
@Null 限制只能爲null
@NotNull 限制必須不爲null
@AssertFalse 限制必須爲false
@AssertTrue 限制必須爲true
@DecimalMax(value) 限制必須爲一個不大於指定值的數字
@DecimalMin(value) 限制必須爲一個不小於指定值的數字
@Digits(integer,fraction) 限制必須爲一個小數,且整數部分的位數不能超過integer,小數部分的位數不能超過fraction
@Future 限制必須是一個將來的日期
@Max(value) 限制必須爲一個不大於指定值的數字
@Min(value) 限制必須爲一個不小於指定值的數字
@Past 限制必須是一個過去的日期
@Pattern(value) 限制必須符合指定的正則表達式
@Size(max,min) 限制字符長度必須在min到max之間
@Past 驗證註解的元素值(日期類型)比當前時間早
@NotEmpty 驗證註解的元素值不爲null且不爲空(字符串長度不爲0、集合大小不爲0)
@NotBlank 驗證註解的元素值不爲空(不爲null、去除首位空格後長度爲0),不同於@NotEmpty,@NotBlank只應用於字符串且在比較時會去除字符串的空格
@Email 驗證註解的元素值是Email,也可以通過正則表達式和flag指定自定義的email格式

除此之外還可以自定義驗證信息的要求,例如下面的 @MyConstraint:

  1. public class User {
  2. private String id;
  3. @MyConstraint(message = "這是一個測試")
  4. private String username;
  5. }

註解的具體內容:

  1. @Constraint(validatedBy = {MyConstraintValidator.class})
  2. @Target({ELementtype.METHOD, ElementType.FIELD})
  3. @Retention(RetentionPolicy.RUNTIME)
  4. public @interface MyConstraint {
  5. String message();
  6. Class<?>[] groups() default {};
  7. Class<? extends Payload>[] payload() default {};
  8. }

下面是校驗器:

  1. public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {
  2. @Autowired
  3. private UserService userService;
  4. @Override
  5. public void initialie(@MyConstraint constarintAnnotation) {
  6. System.out.println("my validator init");
  7. }
  8. @Override
  9. public boolean isValid(Object value, ConstraintValidatorContext context) {
  10. userService.getUserByUsername("seina");
  11. System.out.println("valid");
  12. return false;
  13. }
  14. }

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章