Hibernate Validator是Hibernate提供的一個開源框架,使用注解方式非常方便的實現服務端的數據校驗。
官網:http://hibernate.org/validator/
hibernate Validator 是 Bean Validation 的參考實現 。
Hibernate Validator 提供了 JSR 303 規范中所有內置 constraint(約束) 的實現,除此之外還有一些附加的 constraint。
在日常開發中,Hibernate Validator經常用來驗證bean的字段,基於注解,方便快捷高效。
Bean校驗的注解:
添加maven依賴:
<dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> </dependency>
對象屬性約束:
@Table(name = "tb_user") @Data public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotEmpty(message = "用戶名不能為空") @Length(min = 4, max = 15, message = "用戶名長度必須是4~15位") private String username;// 用戶名 @JsonIgnore @NotEmpty(message = "密碼不能為空") @Length(min = 6, max = 25, message = "密碼長度必須是6~25位") private String password;// 密碼 @Pattern(regexp = "^1[35678]\\d{9}$", message = "手機號格式不正確") private String phone;// 電話 private Date created;// 創建時間 @JsonIgnore private String salt;// 密碼的鹽值 }
使約束生效:
@PostMapping("/register") public ResponseEntity<Void> register(@Valid User user, @RequestParam("code") String code) { userService.register(user, code); return ResponseEntity.status(HttpStatus.CREATED).build(); }