2016-05-25 106 views
0

我有一个以特定格式(dd-MMMM-yy)发送日期字段的窗体,我试图设置我的Spring应用程序,以便它可以自动将日期解析为java.util .Date对象。我接触过使用自定义PropertyEditor解析Spring自定义日期

其中一种方法是,首先创建一个自定义PropertyEditorSupport类将处理与分析我的日期将是从/呼出呼入的形式

public class DateTimeEditor extends PropertyEditorSupport { 
    @Override 
    public void setAsText(String value) { 
     try { 
      setValue(new SimpleDateFormat("dd-MMMM-yy").parse(value)); 
     } catch (Exception ex) { 
      setValue(null); 
     } 
    } 

    @Override 
    public String getAsText() { 
     String stringDate = ""; 
     try { 
      stringDate= new SimpleDateFormat("dd-MMMM-yy").format((Date)getValue()); 
     } catch(Exception ex) { 
      // 
     } 
     return stringDate 
    } 
} 

然后创建一个自定义的PropertyEditorRegistrar的注册以上PropertyEditorSupport处理日期

public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar { 
    @Override 
    public void registerCustomEditors(PropertyEditorRegistry registry) { 
     registry.registerCustomEditor(Date.class, new DateTimeEditor()); 
    } 
} 

在弹簧上下文创建豆

<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer"> 
    <property name="propertyEditorRegistrars"> 
     <list> 
      <bean class="com.test.CustomPropertyEditorRegistrar" /> 
     </list> 
    </property> 
</bean> 

我可以看到多次调用CustomPropertyEditorRegistrar类的方法registerCustomEditors,但DateTimeEditor中的方法(setAsText或getAsText)永远不会被调用。

任何想法为什么?

回答

0

您需要添加编辑器弹簧控制器类绑定...

@InitBinder 
public void initBinder(final WebDataBinder binder) { 
    binder.registerCustomEditor(Date.class, new DateTimeEditor(); 
} 
+0

感谢。理解属性编辑器需要注册到控制器webdatabinder中,编辑器才能用于请求我的控制器。 – JCS