Issue
I've got a bean that has a field of type List among other things.
public List<MyClass> getter() {
return field;
}
public void setter(MyClass[] source) {
this.field = Arrays.asList(source);
}
I've implemented a converter Converter<String, MyClass>
and it works, too. If a string can be converted into MyClass, it's converted, and if not, an exception is thrown, and an instance of FieldError
is included in Errors errors = binder.getBindingResult();
. The problem is, the FieldError#getRejected
method a String
with a comma-separated list of both valid and invalid values, which can be misleading. And without a space, which is just ugly. Like this:
Field has invalid value of "valid,invalid"
while I would prefer
Field has invalid value of "invalid"
In other words, how to get the conversion and validation to work individually on each value?
Solution
Although spring's approach is not very intelligent, it's logically correct. The following code can help you find the invalid value.
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);
}
Answered By - sunshujie