您可以尝试这样的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内获取它,方法与您对第一个和第二个字段名相同并使用它。



