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

【Java从零到架构师第③季】【47】SpringBoot-HibernateValidator

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

【Java从零到架构师第③季】【47】SpringBoot-HibernateValidator


持续学习&持续更新中…

守破离


【Java从零到架构师第③季】【47】SpringBoot-后端校验: HibernateValidator
    • 后端校验: HibernateValidator
    • 方法的Model参数校验
    • 方法的非Model参数校验
    • 常见注解
    • 自定义校验
    • 快速失败
    • 参考

后端校验: HibernateValidator

https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/

https://docs.jboss.org/hibernate/stable/validator/reference/en-US/pdf/hibernate_validator_reference.pdf

方法的Model参数校验

Model:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class DictType {
    //主键
    private Integer id;
    //名称
    @NotBlank(message = "名称不能为空")
    private String name;
    //值
    @NotBlank(message = "值不能为空")
    private String value;
    //简介
    private String intro;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
//@ForeignTable("dict_item")
public class DictItem {
    //主键
    private Integer id;
    //名称
    @NotBlank(message = "名称不能为空")
    private String name;
    //值
    @NotBlank(message = "值不能为空")
    private String value;
    //类型id
    @ForeignField(DictType.class)
    private Integer typeId;
    //排序序号:默认为0,值越大,越优先排列展示
    @Min(value = 0, message = "sn不能为负数")
    private Integer sn;
    //是否禁用:0,不禁用(启用);1,禁用;默认为0
    @Range(min = 0, max = 1, message = "disabled只能是0或1")
    private Short disabled;
}

Controller:

public abstract class BaseController {
    @PostMapping("/save")
    public R save(@Valid T entity) {
        if (!service().saveOrUpdate(entity)) {
            Rs.exception(CodeMsg.SAVE_ERROR);
        }
        return Rs.success(CodeMsg.SAVE_OK);
    }
}

异常处理:

    @ExceptionHandler(Throwable.class)
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public R handle(Throwable throwable) {
        return Rs.error(throwable);
    }
    public static R error(Throwable e) {
        R r = error(e.getMessage()); // 开发阶段
//        R r = error(); // 项目上线 项目上线了就不要把其它异常信息给用户看了
        if (e instanceof CommonException) {
            r.setCode(((CommonException) e).getCode());
        } else if (e instanceof BindException) {
            final List msgs = ((BindException) e).getAllErrors()
                    .stream()
                    .map(ObjectError::getDefaultMessage)
                    .collect(Collectors.toList());
//            final List allErrors = ((BindException) e).getAllErrors();
//            final List msgs = new ArrayList<>();
//            for (ObjectError allError : allErrors) {
//                msgs.add(allError.getDefaultMessage());
//            }
            final String message = StringUtils.collectionToDelimitedString(msgs, ", ");
            r.setMsg(message);
        }
        return r;
    }
方法的非Model参数校验

Controller:

@Validated
public abstract class BaseController {
    @PostMapping("/remove")
    public R remove(@NotBlank(message = "id不能为空") String id) {
        final String[] ids = id.split(",");
        if (!service().removeByIds(Arrays.asList(ids))) {
            Rs.exception(CodeMsg.REMOVE_ERROR);
        }
        return Rs.success(CodeMsg.REMOVE_OK);
    }
}

异常处理:

    public static R error(Throwable e) {
        if (e instanceof CommonException) {
            // ...
        } else if (e instanceof BindException) {
            // ...
        } else if (e instanceof ConstraintViolationException) {
            final List msgs = ((ConstraintViolationException) e).getConstraintViolations()
                    .stream()
                    .map(ConstraintViolation::getMessage)
                    .collect(Collectors.toList());
            final String message = StringUtils.collectionToDelimitedString(msgs, ", ");
            r.setMsg(message);
        }
        return r;
    }
常见注解

自定义校验

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Constraint(validatedBy = BoolNumber.BoolNumberValidator.class)
public @interface BoolNumber {
    String message() default "只能为0或1";
    Class[] groups() default {};
    Class[] payload() default {};

    class BoolNumberValidator implements ConstraintValidator {
        @Override
        public boolean isValid(Short value, ConstraintValidatorContext context) {
            return value == null || value == 0 || value == 1;
        }
    }
}
public class DictItem {
    //是否禁用:0,不禁用(启用);1,禁用;默认为0
//    @Range(min = 0, max = 1, message = "disabled只能是0或1")
    @BoolNumber(message = "disabled只能是0或1")
    private Short disabled;
}
快速失败

@Configuration
public class ValidatorCfg {
    @Bean
    public Validator validator() {
        return Validation
                .byProvider(HibernateValidator.class)
                .configure()
                .failFast(true)
                .buildValidatorFactory().getValidator();
    }
}
参考

小码哥-李明杰: Java从0到架构师③进阶互联网架构师.


本文完,感谢您的关注支持!


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

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

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