I have a problem with the binding of a form input text to a Integer field of the bean to which the form is binded. If I write a wrong number in the input text (eg: “12b”) I have a Binding Exception. So, I set a @InitBinder in my controller in this way:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Integer.class, new CustomIntegerBinder());
}
Where CustomIntegerBinder is implemented as follows:
public class CustomIntegerBinder extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
try {
setValue(Integer.parseInt(text));
} catch (Exception e) {
//I WANT TO ADD ERROR TO THE ERROR LIST!
}
}
@Override
public String getAsText() {
return getValue().toString();
}
}
My question is: how could I succeed in adding a message error to the errors list, so that a conversion error would not cause a crasch of the application, but a message to be printed in the “errors” tag in the jsp?
Thank you!
The
setAsTextmethod should throw anIllegalArgumentException(as the method signature indicates) if the value can’t be set from text.If you throw the
IllegalArgumentExceptionfrom yourcatchthen Spring should add the error for you.