moh
moh

Reputation: 321

Spring 3.1 Form binding with List<Date>

I have a form object

public class TestForm {
 private long id;
 private List<Date> dates;
// getters and setters for the above
}

And my controller has the following..

@RequestMapping(value = "/assignDummy", method = RequestMethod.POST)
public @ResponseBody
String assignDates(TestForm frm) {
    System.out.println("frm:"+frm.getId()+", date:"+frm.getDates());
    return "Everything is fine";
}

My form..

<form name="abc" method="post" action="assignDummy.htm">
<input type="text" name="id" value="1000">
<input type="text" name="dates[0]" value="4500000">
<input type="submit">
</form>

I get the following error..

Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'dates[0]'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.util.Date for value '4500000'; nested exception is java.lang.IllegalArgumentException"

Any help is appreciated. Thanks in advance

Upvotes: 0

Views: 657

Answers (1)

Arnaud Gourlay
Arnaud Gourlay

Reputation: 4666

You are trying to put a String into Date without converting it, so it crashes. You have to use a custom property editor in order to convert the input String into a Date.

Try to add in your controller

 @InitBinder
    public void initBinder(WebDataBinder binder) {
        CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true);
        binder.registerCustomEditor(Date.class, editor);
    }

Upvotes: 2

Related Questions