常见注解
表1. Bean验证中内置的约束
注解 | 解释 |
---|---|
@Null | 被注释的元素必须为 null |
@NotNull | 被注释的元素必须不为 null(用于Integer) |
@AssertTrue | 被注释的元素必须为 true |
@AssertFalse | 被注释的元素必须为 false |
@Min(value) | 被注释的元素必须是一个数字,其值必须大于等于指定的最小值(Integer) |
@Max(value) | 被注释的元素必须是一个数字,其值必须小于等于指定的最大值(Integer) |
@DecimalMin(value) | 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 |
@DecimalMax(value) | 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 |
@Size(max, min) | 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内 |
@Digits (integer, fraction) | 被注释的元素必须是一个数字,其值必须在可接受的范围内 |
@Past | 被注释的元素必须是一个过去的日期 |
@Future | 被注释的元素必须是一个将来的日期 |
表2. Hibernate Validator附加的约束
注解 | 解释 |
---|---|
被注释的元素必须是电子邮箱地址 | |
@Length | 被注释的字符串的大小必须在指定的范围内 |
@NotEmpty | 被注释的字符串的必须非空 |
@Range | 被注释的元素必须在合适的范围内 |
@Pattern(value) | 被注释的元素必须符合指定的正则表达式 |
例:
@Max(value = 20, message = "id长度不合法")
@NotNull(message = "id不能为空")
private Integer invoiceTitleId;
@Size(max=40,message="会员编号长度不能超过{max}位")
@NotBlank(message = "会员编号不能为空")
private String memberNo;
@Pattern(regexp = "^1(3|4|5|7|8)\\d{9}$",message = "手机号码格式错误")
@NotBlank(message = "手机号码不能为空")
private String phone;
@Email(message = "邮箱格式错误")
private String email;
@Min(value = 0, message = "年龄超出范围,最小值为0")
@Max(value = 120, message = "年龄超出范围,最大值为120")
private Integer age;
@Range(min = 0, max = 120, message = "年龄大于等于0小于等于120")
private Integer age;
示例
entity实体
@Data
@ToString(callSuper = true, includeFieldNames = true)
public class MemberParamsReqDto implements Serializable{
@NotNull(message = "id不能为空")
private Integer invoiceTitleId;
@Size(max=40,message="会员编号长度不能超过{max}位")
@NotBlank(message = "会员编号不能为空")
private String memberNo;
@Size(max=40,message="openId长度不能超过{max}位")
@NotBlank(message = "openId不能为空")
private String openId;
}
controller 校验
public String updateDefaultInvoiceTitle(HttpServletRequest request,@RequestBody MemberParamsReqDto reqDto) {
//入参校验
String resultVertify = ValidatorUtils.validateEntity(reqDto);
int statusVertify = new JsonParser().parse(resultVertify).getAsJsonObject().get("status").getAsInt();
if(statusVertify!=0){
return resultVertify;
}
工具类
public class ValidatorUtils {
private static Validator validator;
static {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
/**
* 校验对象
*
* @param object 待校验对象
* @param groups 待校验的组
* @throws YtoException 校验不通过,则报RRException异常
*/
public static String validateEntity(Object object, Class<?>... groups) throws YtoException {
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(";");
}
return CommonUtil.getReturn(msg.toString(), SysErrorConsts.OPERATION_ERROR_CODE, null);
}
return CommonUtil.getReturn(CommonConstants.RESULT_SUCCESS, CommonConstants.RESULT_STATUS_OK, null);
}
}