Search code examples
spring-mvcspring-form

Populate date field in Spring MVC Form


I am building a little Spring MVC (4.2.4.RELEASE) app and I've run into a few problems with date fields.

I can now create objects with dates and I can display the date in text/'open' html. I can't seem to populate an input box of type=date however. Can anyone help me ?

So my pojo has 2 date fields

@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date startDate;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date endDate;

I've added an InitBinder to the controller class

@InitBinder
protected void initBinder(WebDataBinder binder) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(true);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat,false));

}

I'm passing the pojo as a requestAttribute to the view and I don't see any problem here as other fields are displaying.

In the jsp

<table>
    <tr>
        <td>Start Date</td>
        <td><form:input type="date" path="startDate" id="startDate" /></td>
    </tr>
    <tr>
        <td>End Date</td>
        <td><form:input  type="date" path="endDate" id="endDate" /></td>
    </tr>
</table>

The fields are not populated. I'm sure this is a format issue as if I turn them into standard string input boxes by removing type="date" the textboxes are populated with the dates (although not in the format I've specified anywhere!?).

e.g. Tue Mar 01 00:00:00 GMT 2016

Do I need to 'force' the format anywhere else ?


Solution

  • I've found the answer, apologies for answering my own question & also for not putting the vital code in the question... I thought it may be useful as a quick gotcha to others...

    The issue is that Spring only seems to use the @DateTimeFormat annotation when using the Model Interface. I was asked to try and avoid this (no good reason that I could see) and so played with alternatives, settling on HttpServletRequest. Spring did not pick up the date format

        @RequestMapping(value = "/person/edit/{id}", method=RequestMethod.GET) 
        public String getPersonForEdit(@PathVariable("id") long id
                , HttpServletRequest request) throws IOException 
        {  
            ...     
            **request.setAttribute**("person", person);
            return "editPerson";
        }
    

    When the controller used the Model interface

        @RequestMapping(value = "/person/edit/{id}", method=RequestMethod.GET) 
        public String getPersonForEdit(@PathVariable("id") long id
                , **Model model**) throws IOException 
        {  
             ...
             **model.addAttribute**("person", person);
             return "editPerson";
        }
    

    The date format worked fine.