spring 中校验参数的快捷方式
public class ValidatorUtils {
private static Validator validator;
static {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
public static void validateEntity(Object object, Class<?>... groups)
throws CustomeException {
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
if (!constraintViolations.isEmpty()) {
StringBuilder msg = new StringBuilder();
for(ConstraintViolation<Object> constraint: constraintViolations){
msg.append(constraint.getMessage()).append(",");
}
throw new CustomeException(msg.toString());
}
}
}
//在系统entity 类的属性上标识 hibernate validator 注解标识 即可
//例如
@Data
@TableName("sys_user")
public class SysUserEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 用户ID
*/
@TableId
private Long userId;
/**
* 用户名
*/
@NotBlank(message="用户名不能为空", groups = {AddGroup.class, UpdateGroup.class})
private String username;
/**
* 密码
*/
@NotBlank(message="密码不能为空", groups = AddGroup.class)
private String password;
/**
* 盐
*/
private String salt;
/**
* 邮箱
*/
@NotBlank(message="邮箱不能为空", groups = {AddGroup.class, UpdateGroup.class})
@Email(message="邮箱格式不正确", groups = {AddGroup.class, UpdateGroup.class})
private String email;
/**
* 手机号
*/
private String mobile;
/**
* 状态 0:禁用 1:正常
*/
private Integer status;
/**
* 角色ID列表
*/
@TableField(exist=false)
private List<Long> roleIdList;
/**
* 创建者ID
*/
private Long createUserId;
/**
* 创建时间
*/
private Date createTime;
}
1.其中在controller 中校验user validateEntity方法传入user对象 即可进行校验
2.groups 在属性注解中可以添加分组 调用validateEntity传入分组可以指定规则进行校验
网友评论