hibernate-validator使用@NotNull、@NotBlank 没有生效

龚凌
2023-12-01

springboot 2.3之前的集成在spring-boot-starter-web里了,所以不需要额外引入包

springboot 2.3之后需要引入 spring-boot-starter-validation

单个参数校验和Bean字段校验还是有点区别的:单个参数校验需要在参数上增加校验注解,并在Controller上标注@Validated。

这样就可以了

@RestController
@Validated
public class TestAction {

    @RequestMapping("/testException")
    public R testException(@NotNull String code){
        System.out.println(code);
        return R.success("成功");
    }
}

全局异常处理可以加上这些参数:

 @ExceptionHandler(ConstraintViolationException.class)
    public R constraintViolationExceptionHandler(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        List<String> collect = constraintViolations.stream()
                .map(o -> o.getMessage())
                .collect(Collectors.toList());
        return R.error(StringUtils.join(collect,","));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect = fieldErrors.stream()
                .map(o -> o.getDefaultMessage())
                .collect(Collectors.toList());
        return R.error(StringUtils.join(collect,","));
    }

    @ExceptionHandler(BindException.class)
    public R bindExceptionHandler(BindException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect = fieldErrors.stream()
                .map(o -> o.getDefaultMessage())
                .collect(Collectors.toList());
        return R.error(StringUtils.join(collect,","));
    }

对对象进行校验:

@Data
@Validated
public class User {

    @NotNull(message = "用户名不能为空")
    private String userName;
    @NotNull(message = "密码不能为空")
    private String password;
}

@RestController
@Validated
public class TestAction {

    @RequestMapping("/testException")
    public R testException(@NotNull(message = "code不能为空") String code){
        System.out.println(code);
        return R.success("成功");
    }
    @RequestMapping("/testUser")
    public R testUser(@Valid User user){
        System.out.println(user.getUserName()+"--"+user.getPassword());
        return R.success();
    }
}

 类似资料: