3 1.在已有的公共方法中新增一个校验方法
1.新增一个注解类
public static boolean isChineseStr(String str){
Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");
char c[] = str.toCharArray();
for(int i=0;i<c.length;i++){
Matcher matcher = pattern.matcher(String.valueOf(c[i]));
if(!matcher.matches()){
return false;
}
}
return true;
}
2.新增一个注解
@Target({ElementType.METHOD,ElementType.FIELD,ElementType.ANNOTATION_TYPE,ElementType.CONSTRUCTOR,
ElementType.PARAMETER,ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = IsChineseValidator.class)
public @interface IsChineseStr {
//默认手机号码不可为空
boolean required() default true;
//如果校检不通过时提示信息
String message() default "请输入中文姓名";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default {};
}
3.新建注解实现方法
public class IsChineseValidator implements ConstraintValidator<IsChineseStr,String> {
//用于获取校检字段是否可以为空
private boolean required = false;
/**
* 用于获取注解
*
* @param constraintAnnotation
*/
public void initialize(IsMobile constraintAnnotation) {
required = constraintAnnotation.required();
}
/**
* 用于校检字段是否合法
*
* @param value 带校检的字段
* @param constraintValidatorContext
* @return 字段检验结果
*/
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
if (required) {
return ValidatorUtils.isChineseStr(value);//检验结果
} else {
if (StringUtils.isEmpty(value))
return true;
else
return ValidatorUtils.isChineseStr(value);//检验结果
}
}
}
该博客介绍了如何在Java中使用注解新增一个校验方法,验证输入字符串是否为中文。首先创建了一个用于检查中文字符的注解类,然后定义了一个注解`IsChineseStr`,并指定了其验证器`IsChineseValidator`。验证器实现了对输入字符串的校验逻辑,判断每个字符是否属于中文范围。此方法适用于字段、方法等不同元素类型的校验。
1462

被折叠的 条评论
为什么被折叠?



