Bean Validator扩展

Bean Validator扩展

1、需求

​ 在使用validator时,有个需求就是公用错误提示信息,什么意思?

举个例子:

​ @NotEmpty非空判断,在资源文件中我不想每个非空判断都写”不能为空“,只需要写”###“,然后提示信息自动会变成”###不能为空“

代码:

public class {
   //资源文件中user.name.empty=用户名
@NotEmpty(key={user.name.empty})
private String name;
'''
}
//加入name为空,则最终的错误提示为“用户名不能为空”(会自动加上“不能为空”信息)

2、实现方式

有两种实现方式

方式一:手动调用验证方法
注解
@Target({FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@ReportAsSingleViolation
@Constraint(validatedBy = {})
@NotNull
@Size(min = 1)
public @interface NotEmpty {

String message() default "{key}{com.chyjr.hyb.validator.constraints.empty.message}";

Class<?>[] groups() default { };

Class<? extends Payload>[] payload() default { };

String key() default "";
}
验证器

//验证器
public class MyValidator {

private static final Logger log = LoggerFactory.getLogger(HybValidator.class);

   private static Validator validator = null;
   private static MessageInterpolator msgInterpolator = null;
   
   static {
       if (validator == null) {
      LocalValidatorFactoryBean factory =
              (LocalValidatorFactoryBean) ApplicationContextUtil.getBean("validator");
      validator = factory.getValidator();
           msgInterpolator = factory.getMessageInterpolator();
      }
  }

   public static HybValidatorResult validate(Object object, Class<?>... groups) {
  HybValidatorResult result = new HybValidatorResult();
       Set<ConstraintViolation<Object>> violations = validator.validate(object, groups);
       Map<String, String> map = new HashMap<>();
       if (CollectionUtils.isEmpty(violations)) {
           result.setErrors(false);
      } else {
      result.setErrors(true);
           for (ConstraintViolation<Object> violation : violations) {
          String path = violation.getPropertyPath().toString();
          String message = violation.getMessage();
          if (StringUtils.isBlank(path) || StringUtils.isBlank(message) || map.containsKey(path))
          continue;
          message = resolveMessage(message);
          map.put(path, message);
          }
           result.setItems(map);
      }
       return result;
  }
   
private static final Pattern elpattern = Pattern.compile("\\{[^{}]+\\}");

   private static String resolveMessage(String message) {
  Matcher matcher = elpattern.matcher(message);
  try {
  while (matcher.find()) {
  String el = matcher.group();
               //用资源文件信息替换message = {key}{my.empty.message}
               //注解这里的key会替换成注解NotEmpty定义的key,即
               //message = {user.name.empty}{my.empty.message}
版权声明:本文为liruiloveparents原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/liruiloveparents/p/9378264.html