A lot of times I needed to display and edit data that has date information in it. For example, user registration form might have a birthday field. I do want that field to be java.util.Date and be save in the database as a date, but when rendering to JSP I used to have to convert it to/from a text field. Not anymore! I started using custom PropertyEditorSupport for Date processing. To use this feature, you need to follow 3 steps:
First, you need to create a custom PropertyEditorSupport. Here is the one I used for java.util.Date:
package foo;import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.text.ParseException;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
/**
* @author Henry Naftulin
* @since Aug 4, 2008
*/
public class DatePropertyEditor extends PropertyEditorSupport {
Logger log = Logger.getLogger(DatePropertyEditor.class);
String[] formats = {"yyyy-MM-dd", "MM/dd/yyyy", "MM/dd/yy"};
Date defaultDate = new Date(0L);
public void setAsText(String textValue) {
if (textValue == null) {
setValue(defaultDate);
return;
}
Date retDate = defaultDate;
try {
retDate = DateUtils.parseDate(textValue, formats);
} catch (ParseException e) {
log.error("Cannot parse " + textValue + " as date.", e);
}
setValue(retDate);
}
}
Second, I need to register the custom property editor with my Spring MVC controller, which I do by overwriting the following method:
protected void initBinder(HttpServletRequest req, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Date.class, new DatePropertyEditor());
}
And that is it: you can just render you date field in the JSP and dates typed into the text fields would be converted from the String representation to java.util.Date!