栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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> constraintViolations = e.getConstraintViolations();
        List 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 fieldErrors = e.getBindingResult().getFieldErrors();
        List 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 fieldErrors = e.getBindingResult().getFieldErrors();
        List 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();
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/710794.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号