Tuesday, July 1, 2008

Date Binding on SimpleFormController using initBinder

If you wish to bind an input date field in your web form directly to a Date property in your command object, you will need to override the initBinder method of the SimpleFormController. Following maps a date in dd/MM/yyyy format on the front-end to backend and vice-versa.

@Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder dataBinder) throws Exception{
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setLenient(false);
dataBinder.registerCustomEditor(Date.class,new CustomDateEditor(df,false));
super.initBinder(request,dataBinder);
}

Your valang validators can help you put some crisp checks on date if need be. Remember dd/mm/yyyy and dd/MM/yyyy are NOT same.

No comments: