JSR 303

类是转载的,不知道转的哪里的。

此类依赖 JSR 303 – Bean Validation, Hibernate Validator。

代码不能直接运行。意会一下。自己改改。

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mmall.exception.ParamException;
import org.apache.commons.collections.MapUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;

public class BeanValidator {

    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    public static <T> Map<String, String> validate(T t, Class... groups) {
        Validator validator = validatorFactory.getValidator();
        Set validateResult = validator.validate(t, groups);
        if (validateResult.isEmpty()) {
            return Collections.emptyMap();
        } else {
            LinkedHashMap errors = Maps.newLinkedHashMap();
            Iterator iterator = validateResult.iterator();
            while (iterator.hasNext()) {
                ConstraintViolation violation = (ConstraintViolation)iterator.next();
                errors.put(violation.getPropertyPath().toString(), violation.getMessage());
            }
            return errors;
        }
    }

    public static Map<String, String> validateList(Collection<?> collection) {
        Preconditions.checkNotNull(collection);
        Iterator iterator = collection.iterator();
        Map errors;

        do {
            if (!iterator.hasNext()) {
                return Collections.emptyMap();
            }
            Object object = iterator.next();
            errors = validate(object, new Class[0]);
        } while (errors.isEmpty());

        return errors;
    }

    public static Map<String, String> validateObject(Object first, Object... objects) {
        if (objects != null && objects.length > 0) {
            return validateList(Lists.asList(first, objects));
        } else {
            return validate(first, new Class[0]);
        }
    }

    public static void check(Object param) throws ParamException {
        Map<String, String> map = BeanValidator.validateObject(param);
        if (MapUtils.isNotEmpty(map)) {
            throw new ParamException(map.toString());
        }
    }
}

校验注解

空检查

  • @Null:限制只能为 null
  • @NotNull:限制不能为 null
  • @NotEmpty:不为 null 且不为空(字符串长度不为0、集合大小不为0)
  • @NotBlank:不为空(不为 null、去除首位空格后的长度为0,与@NotEmpty不同的是字符串比较时会去除字符串的空格)

Boolean检查

  • @AssertFalse:限制必须为false
  • @AssertTrue:限制必须为true

长度检查

  • @Size(max,min):限制长度必须在 min 到 max 之间
  • @Length(min=,max=):长度在 min 到 max 之间

日期检查

  • @Past:验证注解的元素值(日期类型)比当前时间早
  • @Future:限制必须为一个将来的日期
  • @Pattern(value):限制必须符合制定的正则表达式

数值检查

  • @Max(value):限制必须为一个大于指定值的数字
  • @Min(value):限制必须为一个小于指定值的数字
  • @DecimalMax(value):限制必须为一个大于指定值的数字
  • @DecimalMin(value):限制必须为一个小于指定值的数字
  • @Range(min=, max=) :数值在 min 到 max 之间
  • @Digits(integer,fraction):限制必须为一个小数,整数部分位数不能超过integer,小数部分不能超过 fraction

其它检查

  • @Email:验证元素的值时Email
  • @URL(protocol=,host=, port=,regexp=, flags=):请求地址、端口、主机检查


作者:林塬
链接:https://www.jianshu.com/p/f85c248294f6
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
 
 
下面是 具体的规范

Bean Validation 中的 constraint

表 1. Bean Validation 中内置的 constraint
表 2. Hibernate Validator 附加的 constraint

定制化的 constraint

@Price是一个定制化的 constraint,由两个内置的 constraint 组合而成。

清单 4. @Price 的 annotation 部分
1
2
3
4
5
6
7
8
9
10
11
12
// @Max 和 @Min 都是内置的 constraint
@Max(10000)
@Min(8000)
@Constraint(validatedBy = {})
@Documented
@Target( { ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Price {
String message() default "错误的价格";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

@Status是一个新开发的 constraint.

清单 5. @Status 的 annotation 部分
1
2
3
4
5
6
7
8
9
@Constraint(validatedBy = {StatusValidator.class})
@Documented
@Target( { ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Status {
String message() default "不正确的状态 , 应该是 'created', 'paid', shipped', closed'其中之一";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
清单 6. @Status 的 constraint validator 部分
1
2
3
4
5
6
7
8
9
10
public class StatusValidator implements ConstraintValidator<Status, String>{
private final String[] ALL_STATUS = {"created", "paid", "shipped", "closed"};
public void initialize(Status status) {
}
public boolean isValid(String value, ConstraintValidatorContext context) {
if(Arrays.asList(ALL_STATUS).contains(value))
return true;
return false;
}
}
JRS 303 Bean Validation  转载看这里   https://www.ibm.com/developerworks/cn/java/j-lo-jsr303/
原文地址:https://www.cnblogs.com/chengjunchao/p/9648245.html