Springboot采用hibernate-validate验证请求参数

在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

原文地址:https://www.cnblogs.com/moris5013/p/11133048.html