持续学习&持续更新中…
守破离
【Java从零到架构师第③季】【47】SpringBoot-后端校验: HibernateValidator
- 后端校验: HibernateValidator
- 方法的Model参数校验
- 方法的非Model参数校验
- 常见注解
- 自定义校验
- 快速失败
- 参考
https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/
方法的Model参数校验https://docs.jboss.org/hibernate/stable/validator/reference/en-US/pdf/hibernate_validator_reference.pdf
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 extends Payload>[] 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到架构师③进阶互联网架构师.
本文完,感谢您的关注支持!



