开发者

Bind XMLGregorianCalendar field in Spring MVC with velocity

开发者 https://www.devze.com 2022-12-24 19:21 出处:网络
I have a model object with an XMLGregorianCalendar field. How can I bi开发者_如何学Pythonnd it to an input field?

I have a model object with an XMLGregorianCalendar field. How can I bi开发者_如何学Pythonnd it to an input field?

For string fields I'm using:

#springFormInput("model.object.stringfield" "")

but can't work out the corresponding code for an XMLGregorianCalendar


You may be better off converting the XMLGregorianCalendar to something easier to handle like Calendar or Date before handing it off to the presentation layer.


Here's a solution. It uses jodatime but could probably be changed not to:

For the view (velocity in this case):

#springFormInput("model.object.xmlgregoriancalendar.field" "")

For the controller:

@InitBinder
public void binder(WebDataBinder binder) {
    binder.registerCustomEditor(XMLGregorianCalendar.class, new PropertyEditorSupport() {
       public void setAsText(String value) {
           setValue(createXMLGregorianCalendar(value));
        }

        public String getAsText() {
            return new SimpleDateFormat("dd/MM/yyyy").format(((XMLGregorianCalendar)getValue()).toGregorianCalendar().getTime());
        }  
    });
}

private XMLGregorianCalendar createXMLGregorianCalendar(String date) {
    LocalDateTime result = DateTimeFormat.forPattern("dd/MM/yyyy").parseDateTime(date).toLocalDateTime();
    return xmlDF().newXMLGregorianCalendar(result.toDateTime().toGregorianCalendar());
}


private static DatatypeFactory xmlDF() {
    try {
        return DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException ex) {
        throw new RuntimeException(ex);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消