Spring验证-类级别验证以解决字段错误 [英] Spring Validation - Class level validation to address field errors
问题描述
如果我们定义一个类级别的验证注释,例如一个比较字段并具有ConstraintValidator
这样的注释:
If we define a class level validation annotation, such as one which compare fields and have a ConstraintValidator
like this:
public class ComparisonValidator implements ConstraintValidator<ValueMatches, Object>
{
private String[] fields;
@Override
public void initialize(final ValueMatches constraintAnnotation) {
fields = constraintAnnotation.fields();
}
@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
if (fields.length == 0) {
return true;
}
final BeanWrapperImpl beanWrapper = new BeanWrapperImpl(value);
final Object comparisonValue = beanWrapper.getPropertyValue(fields[0]);
for (int i = 1; i < fields.length; i++) {
final Object fieldValue = beanWrapper.getPropertyValue(fields[i]);
if (!comparisonValue.equals(fieldValue)) {
return false;
}
}
return true;
}
}
我们很好地产生了一个全局验证错误,可以通过Thymeleaf使用以下方法进行访问:
${#fields.errors('global')}
We well produce a Global validation error, accessible via Thymeleaf using:
${#fields.errors('global')}
现在,我如何识别该错误并了解它是特定的比较错误?我的意思是,毕竟我们会收到有关全局错误的消息,还是我错了?
Now, how can I identify that error and understand it is the specific comparison error? I mean, after all we get a message for global errors, or am I wrong?
推荐答案
该死,Spring文档! 这很简单,但并不是很容易理解.
Damn you, Spring documentation! It is fairly simple, but not really understandable.
@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
if (fields.length > 0) {
final BeanWrapperImpl beanWrapper = new BeanWrapperImpl(value);
final Object comparisonValue = beanWrapper.getPropertyValue(fields[0]);
for (int i = 1; i < fields.length; i++) {
if (!comparisonValue.equals(beanWrapper.getPropertyValue(fields[i]))) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(errorMessage).addPropertyNode(fields[0]).addConstraintViolation();
return false;
}
}
}
return true;
}
方法disableDefaultConstraintViolation()
告诉ConstrainValidatorContext
通过使用注释本身不产生约束违反对象.
The method disableDefaultConstraintViolation()
tells the ConstrainValidatorContext
to not produce the constraint violation object by using the annotation itself.
然后您可以通过buildConstraintViolationWithTemplate()
方法产生自定义约束违规.
You can then produce a custom constraint violation via the buildConstraintViolationWithTemplate()
method.
这篇关于Spring验证-类级别验证以解决字段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!