依賴
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.5.Final</version>
</dependency>
常見的使用實例
//該參數(shù)必須為空
@Null(message = "無需ID")
private Integer id;
//根據(jù)正則校驗手機號是否是由數(shù)字組成
@Pattern(regexp = "^\\d{11}$", message = "手機格式不正確,不是11位")
private String telephone;
//校驗該對象是否為null
//對于String來說,空字符串可通過校驗,所以String應(yīng)該使用@NotBlank進(jìn)行校驗,此處僅做示例而已。
@NotNull(message = "聯(lián)系人不能為空")
private String friendName;
//校驗對象是否是空對象,可用于Array,Collection,Map,String
@NotEmpty(message = "家庭成員不能為空")
private List families;
//校驗長度,可以用于Array,Collection,Map,String
@Size(min = 4, max = 8, message = "用戶名長度錯誤 by size")
//校驗長度,只能用于String
@Length(min = 4, max = 8, message = "用戶名長度錯誤 by length")
private String username;
//javax校驗
@Max(value = 200, message = "年齡一般不會超過200 by max")
@Min(value = 1, message = "年齡一般不能小于1 by min")
//hibernate校驗,效果等同
@Range(min = 0, max = 200, message = "年齡范圍在0-200之間 by range")
private Integer age;
//校驗參數(shù)是否是False, 相反的是@AssertTrue
@AssertFalse(message = "用戶初始化無需凍結(jié)")
private Boolean lock;
//String專用
@NotBlank(message = "密碼不能為空")
@Size(min = 6, max = 12, message = "密碼長度不對")
private String password;
//使用自定義校驗注解->校驗時間
@Past(message = "生日只能為以前的時間")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
private Date birth;
//校驗Email
@Email(message = "郵件地址不正確")
private String email;
普通參數(shù)的使用方法
- 在類上加@Validated注解
- 在參數(shù)上加上校驗注解
分組校驗
我們有一個用戶DTO,其中有id,username兩個屬性。當(dāng)保存時,id不需要有值,由數(shù)據(jù)庫自動生成,我們使用@Null注解校驗。當(dāng)更新時,id需要有值,根據(jù)ID去更新用戶名,我們使用@NotNull注解校驗。無論是保存用戶還是更新用戶,都需要校驗用戶名,我們使用@NotBlank注解校驗。
public class UserGroupValidDTO {
public interface SaveGroup extends Default {}
public interface UpdateGroup extends Default {}
@Null(groups = {SaveGroup.class}, message = "不需要傳入用戶ID")
@NotNull(groups = {UpdateGroup.class}, message = "用戶ID不能為空")
private Integer id;
@NotBlank(message = "用戶名不能為空")
private String username;
//Setter Getter ...
}
定義相應(yīng)類型的公開接口(SaveGroup,UpdateGroup),給每個校驗注解指定groups屬性,如果不指定則默認(rèn)為javax.validation.groups.Default.class。
UserController
@Validated
@RestController
@RequestMapping(value = "/user")
public class UserController {
/**
* 分組校驗:保存用戶,不能傳ID
*/
@PostMapping("/save")
public void validSaveUser(@RequestBody @Validated(value = UserGroupValidDTO.SaveGroup.class) UserGroupValidDTO userDTO) {
//save user
}
/**
* 分組校驗:更新用戶信息,需要傳ID
*/
@PostMapping("/update")
public void validUpdateUser(@RequestBody @Validated(value = UserGroupValidDTO.UpdateGroup.class) UserGroupValidDTO userDTO) {
//update user
}
}
自定義注解
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PastTimeValidate.class)
public @interface PastDate {
String message();
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
編寫校驗規(guī)則
校驗規(guī)則也就是枚舉PastDate中指定的validateBy屬性
public class PastTimeValidate implements ConstraintValidator<PastDate, LocalDateTime> {
@Override
public void initialize(PastDate constraintAnnotation) {
log.info("init enum PastDate");
}
@Override
public boolean isValid(LocalDateTime localDateTime, ConstraintValidatorContext context) {
return localDateTime.isBefore(LocalDateTime.now()) ? true : false;
}
}
依賴異常統(tǒng)一返回json結(jié)果
@ControllerAdvice
public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BindException.class)
@ResponseBody
public Object paramCheckExceptionHandler(BindException e) {
BindingResult bindingResult = e.getBindingResult();
return CommonJsonResultBuilder.builder().code(400).data("error", getErrors(bindingResult)).message("參數(shù)錯誤").build();
}
private Map<String, Object> getErrors(BindingResult result) {
Map<String, Object> map = new HashMap<>();
List<FieldError> list = result.getFieldErrors();
for (FieldError error : list) {
map.put(error.getField(), error.getDefaultMessage());
}
return map;
}
}
controller
@Slf4j
@RestController
public class VideoController {
@RequestMapping("video/edit")
public CommonJsonResult add(@Valid VideoVO videoVO) {
}
}
VideoVO
public class VideoVO implements Serializable {
private Integer id;
private Integer shopId;
@NotEmpty(message = "視頻標(biāo)題不能為空")
private String title;
@NotNull(message = "視頻Id不能為空")
private Long videoId;
@NotEmpty(message = "視頻路徑不能為空")
private String videoUrl;
@NotEmpty(message = "視頻封面圖不能為空")
private String coverPic;
@NotNull(message = "視頻順序不能為空")
private Integer orderNo;
@NotNull(message = "視頻大小不能為空")
private Long videoSize;
@NotNull(message = "視頻時長不能為空")
private Long timeSize;
}
返回結(jié)果:
{
"code": 400,
"success": false,
"message": "參數(shù)錯誤",
"data": {
"error": {
"timeSize": "視頻時長不能為空",
"orderNo": "視頻順序不能為空",
"videoUrl": "視頻路徑不能為空",
"videoId": "視頻Id不能為空",
"coverPic": "視頻封面圖不能為空",
"title": "視頻標(biāo)題不能為空",
"videoSize": "視頻大小不能為空"
}
}
}