Reputation: 4121
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 year
to int
value 0
Create a custom error message : organizer.year.invalid
Upvotes: 5
Views: 9183
Reputation: 27614
Change int
to Integer
. This is an auto-boxing issue. Since year
is empty, it can't be converted to a primitive value (as you have not specified a default value).
Then you can annotate it @NotNull
to get the validation you want.
Upvotes: 7
Reputation: 2767
first , try to run your application in debug mode and find out exact line at which it's throwing error and provide exact details
I think there must be a problem with your datatype (declaration in form)
If you are using hibernate ,check your hibernate entity class.
and check for datatype of year attribute.
Upvotes: 0