1、编写一个自定义的校验注解,可以参考官方提供的javax.validation.constraints包下的注解
java
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Documented
// 指定使用哪个自定义的校验器进行校验
@Constraint(validatedBy = {ListValueConstraintValidator.class})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
public @interface ListValue {
/**
* JSR303规定必须包含message、groups和payload
*/
// 国际化消息会自动去classpath下名为ValidationMessages.properties的文件中查找对应的key
String message() default "{org.hxr.common.validator.constraints.ListValue.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/**
* 指定可用的范围值
*/
int[] vals() default {};
}
2、编写一个自定义的校验器
java
import org.hxr.common.validator.constraints.ListValue;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;
public class ListValueConstraintValidator implements ConstraintValidator<ListValue, Integer> {
private Set<Integer> set = new HashSet<>();
/**
* 初始化
* @param constraintAnnotation annotation instance for a given constraint declaration
*/
@Override
public void initialize(ListValue constraintAnnotation) {
int[] vals = constraintAnnotation.vals();
if (vals != null) {
for (int val : vals) {
set.add(val);
}
}
}
/**
*
* @param value 需要校验的controller值
* @param context context in which the constraint is evaluated
*
* @return
*/
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
return set.contains(value);
}
}
3、在自定义注解中关联自定义校验器,见1@Constraint