Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-mvc won't bind my request parameter to int

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

like image 737
Tommy Avatar asked May 07 '12 11:05

Tommy


1 Answers

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.

like image 197
pap Avatar answered Sep 23 '22 04:09

pap