我有一个 bean,其中有一个 List 类型的字段。
public List<MyClass> getter() {
return field;
}
public void setter(MyClass[] source) {
this.field = Arrays.asList(source);
}
我已经实现了一个转换器Converter<String, MyClass>
它也有效。如果字符串可以转换为 MyClass,则进行转换,如果不能,则抛出异常,并生成 FieldError
的实例。包含在Errors errors = binder.getBindingResult();
中。问题是,FieldError#getRejected
方法一String
包含有效值和无效值的逗号分隔列表,这可能会产生误导。而且没有空格,这太难看了。像这样:
Field has invalid value of "valid,invalid"
虽然我更愿意
Field has invalid value of "invalid"
换句话说,如何让转换和验证对每个值单独进行?
最佳答案
虽然spring的做法不是很智能,但是逻辑上是正确的。以下代码可以帮助您找到无效值。
FieldError fieldError = bindingResult.getFieldError();
if (fieldError != null && fieldError.contains(TypeMismatchException.class)) {
TypeMismatchException typeMismatchException = fieldError.unwrap(TypeMismatchException.class);
ConversionFailedException conversionFailedException = findConversionFailedException(typeMismatchException);
if (conversionFailedException != null) {
Object value = conversionFailedException.getValue();
// get the invalid field value
}
}
/**
* Recursively find the ConversionFailedException
* @param target
* @return
*/
public ConversionFailedException findConversionFailedException(Throwable target) {
Throwable cause = target.getCause();
if (cause == null) {
return null;
} else if (cause instanceof ConversionFailedException) {
return (ConversionFailedException)cause;
}
return findConversionFailedException(target);
}
关于java - Spring转换器、 validator 和DataBinder : how to handle multivalued bean fields individually?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58134993/