代码之家  ›  专栏  ›  技术社区  ›  Mark Pope

用velocity绑定Spring MVC中的XMLGregorianCalendar场

  •  0
  • Mark Pope  · 技术社区  · 14 年前

    对于我使用的字符串字段:

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

    但无法为XMLGregorianCalendar计算出相应的代码

    2 回复  |  直到 14 年前
        1
  •  0
  •   Community paulsm4    7 年前

    最好将XMLGregorianCalendar转换为更易于处理的格式,如 Calendar or Date 在交给表示层之前。

        2
  •  0
  •   Mark Pope    14 年前

    这里有一个解决方案。它使用jodatime,但可能更改为不:

    对于视图(本例中为速度):

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

    对于控制器:

    @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);
        }
    }