validator中文文档地址和英文地址
https://docs.jboss.org/hibernate/validator/4.2/reference/zh-CN/html/validator-gettingstarted.html
https://docs.jboss.org/hibernate/validator/6.0/reference/en-US/html_single/#preface
自定义hibernate-validator校验
工具类ValidatorUtils
/**
* hibernate-validator校验工具类
* 参考文档:http://docs.jboss.org/hibernate/validator/6.0/reference/en-US/html_single/
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
public class ValidatorUtils {
private static ResourceBundleMessageSource getMessageSource() {
ResourceBundleMessageSource bundleMessageSource = new ResourceBundleMessageSource();
bundleMessageSource.setDefaultEncoding("UTF-8");
bundleMessageSource.setBasenames("i18n/validation", "i18n/validation_common");
return bundleMessageSource;
}
/**
* 校验对象
* @param object 待校验对象
* @param groups 待校验的组
* @throws RenException 校验不通过,则报RenException异常
*/
public static void validateEntity(Object object, Class<?>... groups)
throws RenException {
Locale.setDefault(LocaleContextHolder.getLocale());
Validator validator = Validation.byDefaultProvider().configure().messageInterpolator(
new ResourceBundleMessageInterpolator(new MessageSourceResourceBundleLocator(getMessageSource())))
.buildValidatorFactory().getValidator();
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
if (!constraintViolations.isEmpty()) {
ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
throw new RenException(constraint.getMessage());
}
}
}
// 自定义资源绑定指定的properties文件
ResourceBundleMessageSource bundleMessageSource = new ResourceBundleMessageSource();
bundleMessageSource.setDefaultEncoding("UTF-8");
bundleMessageSource.setBasenames("i18n/validation", "i18n/validation_common");
添加约束
/**
* 用户管理
*/
@Data
@ApiModel(value = "用户管理")
public class SysUserDTO implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "id")
@Null(message="{id.null}", groups = AddGroup.class)
@NotNull(message="{id.require}", groups = UpdateGroup.class)
private Long id;
@ApiModelProperty(value = "用户名", required = true)
@NotBlank(message="{sysuser.username.require}", groups = DefaultGroup.class)
private String username;
@ApiModelProperty(value = "密码")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@NotBlank(message="{sysuser.password.require}", groups = AddGroup.class)
private String password;
@ApiModelProperty(value = "姓名", required = true)
@NotBlank(message="{sysuser.realname.require}", groups = DefaultGroup.class)
private String realName;
@ApiModelProperty(value = "头像")
private String headUrl;
@ApiModelProperty(value = "性别 0:男 1:女 2:保密", required = true)
@Range(min=0, max=2, message = "{sysuser.gender.range}", groups = DefaultGroup.class)
private Integer gender;
@ApiModelProperty(value = "邮箱", required = true)
@NotBlank(message="{sysuser.email.require}", groups = DefaultGroup.class)
@Email(message="{sysuser.email.error}", groups = DefaultGroup.class)
private String email;
@ApiModelProperty(value = "手机号", required = true)
@NotBlank(message="{sysuser.mobile.require}", groups = DefaultGroup.class)
private String mobile;
@ApiModelProperty(value = "部门ID", required = true)
@NotNull(message="{sysuser.deptId.require}", groups = DefaultGroup.class)
private Long deptId;
@ApiModelProperty(value = "超级管理员 0:否 1:是")
@Range(min=0, max=1, message = "{sysuser.superadmin.range}", groups = DefaultGroup.class)
private Integer superAdmin;
@ApiModelProperty(value = "状态 0:停用 1:正常", required = true)
@Range(min=0, max=1, message = "{sysuser.status.range}", groups = DefaultGroup.class)
private Integer status;
@ApiModelProperty(value = "备注")
private String remark;
@ApiModelProperty(value = "创建时间")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
@JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN)
private Date createDate;
@ApiModelProperty(value = "角色ID列表")
private List<Long> roleIdList;
@ApiModelProperty(value = "岗位ID列表")
private List<Long> postIdList;
@ApiModelProperty(value = "部门名称")
private String deptName;
}
校验约束
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
Car car = new Car(null, "DD-AB-123", 4);
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(car);
// validator.validate(car, DefaultGroup.class);
if (!constraintViolations.isEmpty()) {
ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
throw new RenException(constraint.getMessage());
}
// validate()方法会返回一个set的ConstraintViolation的实例的集合, 我们可以通过遍历它来查看有哪些验证错误, 如果一个对象没有校验出问题的话,那么validate() 会返回一个空的set对象
assertEquals(1, constraintViolations.size());
assertEquals("may not be null", constraintViolations.iterator().next().getMessage());
Controller使用
新增和修改都需要校验对象数据使用 ValidatorUtils.validateEntity
校验工具,如果是校验单个值使用AssertUtils.isArrayEmpty
断言工具
@RestController
@RequestMapping("post")
@Api(tags="岗位管理")
public class SysPostController {
@Autowired
private SysPostService sysPostService;
@PostMapping
@ApiOperation("保存")
@LogOperation("保存")
@PreAuthorize("hasAuthority('sys:post:save')")
public Result save(@RequestBody SysPostDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
sysPostService.save(dto);
return new Result();
}
}
@PutMapping
@ApiOperation("修改")
@LogOperation("修改")
@PreAuthorize("hasAuthority('sys:post:update')")
public Result update(@RequestBody SysPostDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
sysPostService.update(dto);
return new Result();
}
@DeleteMapping
@ApiOperation("删除")
@LogOperation("删除")
@PreAuthorize("hasAuthority('sys:post:delete')")
public Result delete(@RequestBody Long[] ids){
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
sysPostService.delete(ids);
return new Result();
}