参数需存在于实体类中,一般专门写一个专门用于接收前端参数的实体类
@Valid
注解开启验证
常见注解
不做赘述。
@Pattern
内容限制 regexp 限制条件的正则表达式。
[\w\u4e00-\u9fa5]+ :限制特殊字符 %¥……&*
自定义注解
@Documented //这个注解不知道是什么意思
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = AreaCodeCheck.AreaCodeCheckValidator.class)
public @interface AreaCodeCheck {
String message() default "行政区划代码格式不正确";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
class AreaCodeCheckValidator implements ConstraintValidator<AreaCodeCheck, String> {
@Override
public void initialize(AreaCodeCheck constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) return true;
if (value.isEmpty()) return true;
return Pattern.matches("[0-9]{6}", value);
}
}
}