栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用HibernateValidator进行跨字段验证不会显示任何错误消息

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用HibernateValidator进行跨字段验证不会显示任何错误消息

您可以尝试这样的isValid方法吗?(这肯定对我在现场项目中起作用):

 public boolean isValid(final Object value, final ConstraintValidatorContext cvc){    boolean toReturn = false;    try{        final Object firstObj = BeanUtils.getProperty(value, firstFieldName );        final Object secondObj = BeanUtils.getProperty(value, secondFieldName );        //System.out.println("firstObj = "+firstObj+"   secondObj = "+secondObj);        toReturn = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);    }    catch (final Exception e){        System.out.println(e.toString());    }    //If the validation failed    if(!toReturn) {        cvc.disableDefaultConstraintViolation();        //In the initialiaze method you get the errorMessage: constraintAnnotation.message();        cvc.buildConstraintViolationWithTemplate(errorMessage).addNode(firstFieldName).addConstraintViolation();    }    return toReturn;}

我还看到您实际上是使用 Object 实现ConstraintValidator接口。它应该是表单中的支持对象:

tempBean //您实际上在commandName中指定的那个。

因此,您的实现应如下所示:

 implements ConstraintValidator<FieldMatch, TempBean>

这可能不是这里的问题,但是作为将来的参考,应该是这样。

更新

在FieldMatch接口/注释中,您有两种方法:第一种和第二种,例如,再添加一个称为errorMessage的方法:

  Class<? extends Payload>[] payload() default {};String first();String second();String errorMessage

在Validation类的方法内部查看-您将在那里获得第一个和第二个字段名称。因此,只需添加errorMessage,例如:

  private String firstFieldName;  private String secondFieldName;  //get the error message name  private String errorMessagename; public void initialize(final FieldMatch constraintAnnotation){    firstFieldName = constraintAnnotation.first();    secondFieldName = constraintAnnotation.second();    errorMessageNAme = constraintAnnotation.errorMessage();    //System.out.println("firstFieldName = "+firstFieldName+"   secondFieldName = "+secondFieldName);}

在isValida内获取它,方法与您对第一个和第二个字段名相同并使用它。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/372497.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号