在springboot項目使用hibernate-validate對請求參數添加注解進行校驗
常用注解
@Null
,標注的屬性值必須為空
@NotNull
,標注的屬性值不能為空
@AssertTrue
,標注的屬性值必須為true
@AssertFalse
,標注的屬性值必須為false
@Min
,標注的屬性值不能小於min中指定的值
@Max
,標注的屬性值不能大於max中指定的值
@DecimalMin
,小數值,同上
@DecimalMax
,小數值,同上
@Negative
,負數
@NegativeOrZero
,0或者負數
@Positive
,整數
@PositiveOrZero
,0或者整數
@Size
,指定字符串長度,注意是長度,有兩個值,min以及max,用於指定最小以及最大長度
@Digits
,內容必須是數字
@Past
,時間必須是過去的時間
@PastOrPresent
,過去或者現在的時間
@Future
,將來的時間
@FutureOrPresent
,將來或者現在的時間
@Pattern
,用於指定一個正則表達式
@NotEmpty
,字符串內容非空
@NotBlank
,字符串內容非空且長度大於0
@Email
,郵箱
@Range
,用於指定數字,注意是數字的范圍,有兩個值,min以及max
使用方法
修改默認的驗證策略
@Configuration public class ValidatorConfig { @Bean public Validator validator() { ValidatorFactory factory = Validation.byProvider(HibernateValidator.class) .configure() //該配置的意思是,有一個驗證失敗就立刻返回,不用等到所有的都驗證完 .addProperty("hibernate.validator.fail_fast", "true") .buildValidatorFactory(); return factory.getValidator(); } }
異常捕獲
@RestControllerAdvice public class GlobalExceptionHandler { //這里處理@RequestBody ,驗證不通過拋出的異常 @ExceptionHandler(MethodArgumentNotValidException.class) public ResultInfo<?> validationErrorHandler(MethodArgumentNotValidException ex) { List<String> errorInformation = ex.getBindingResult().getAllErrors() .stream() .map(ObjectError::getDefaultMessage) .collect(Collectors.toList()); return new ResultInfo<>(400, errorInformation.get(0).toString(), null); } //這里是處理 @PathVariable和@RequestParam 驗證不通過拋出的異常 @ExceptionHandler(ConstraintViolationException.class) public ResultInfo<?> validationErrorHandler(ConstraintViolationException ex) { List<String> errorInformation = ex.getConstraintViolations() .stream() .map(ConstraintViolation::getMessage) .collect(Collectors.toList()); return new ResultInfo<>(400, errorInformation.toString(), null); } }
controller層
@RestController @RequestMapping("/users") @Validated public class UserController { @PostMapping("/addUser") public User addUser(@Valid @RequestBody User user) { // 僅測試驗證過程,省略其他的邏輯 return user; } @GetMapping("/{name}/detail") public User getUserByName( @NotNull @Size(min = 1, max = 5, message = "用戶名格式有誤") @PathVariable String name) { User user = new User(); user.setName(name); return user; } @GetMapping("/getName/detail") public User getUserByNameParam( @NotNull @Size(min = 1, max = 4, message = "用戶名格式有誤") @RequestParam("name") String name) { User user = new User(); user.setName(name); return user; } }
github下載地址:https://github.com/jake1263/hibernate-validate