I have this form with the parameter year and name:
/register?year=&name=test
My class looks like this:
public class Organizer {
private String name;
private int year;
My controller maps those two parameters to my class Organizer
@RequestMapping("/register")
public String register(@Valid Organizer organizer, BindingResult errors...
The problem is binding the parameter year to int. Spring gives me the error
Failed to convert property value of type ‘java.lang.String’ to required type ‘int’ for property ‘year’; nested exception is java.lang.IllegalArgumentException:
I figured out how to add my own custom property editor, but getValue() never seems to be called
@InitBinder
public void binder(WebDataBinder binder) {
binder.registerCustomEditor(int.class, new CustomIntEditor());
}
public class CustomIntEditor extends PropertyEditorSupport {
I thought I would be able to return the int value 0 when the year parameter was anything other than an int value (Integer.parseInt() -> catch exception)
@Override
public void setAsText(String text) throws IllegalArgumentException {
//Some parsing and error handling
setValue((int)0);
}
I would like to be able to:
-
Set the field
yeartointvalue0 -
Create a custom error message :
organizer.year.invalid
Change
inttoInteger. This is an auto-boxing issue. Sinceyearis empty, it can’t be converted to a primitive value (as you have not specified a default value).Then you can annotate it
@NotNullto get the validation you want.