您的位置:首页 > 编程语言 > Java开发

springMVC 前后台日期格式传值解决方式之二(共二) @InitBinder的使用

2015-07-31 11:27 731 查看
关于springmvc日期问题的解决方式 除了本博客的【springMVC 前后台日期格式传值解决方式之 @DateTimeFormat的使用和配置】一文,

还有如下这种方式:

在Controller里加上这段代码:

@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
/**
* 自动转换日期类型的字段格式
*/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));

}


注意,如果前台有多重日期格式,写成类似下面的方式是没有什么卵用的

@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
/**
* 自动转换日期类型的字段格式
*/
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月");
try {
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf2, true));
}catch(Exception e) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf1, true));
}

}


怎么解决呢?

可参考这个问题:http://bbs.csdn.net/topics/380055180

原文内容如下

----------------------------------------------------------分界线开始-----------------------------------------------------------

配置文件为

MyBindingInitializer中,initBinder方法里的

binder.registerCustomEditor(Date.class, new XXXEditor());

在XXXEditor的setAsText方法中,使用系统所有可能用到的format格式一一尝试,捕获异常,最后正确绑定。

-------------------------------------------------------分界线结束----------------------------------------------------------------

至于其中的XXXEditor怎么写,大家可以参照例子中的CustomDateEditor,即:org.springframework.beans.propertyeditors.CustomDateEditor源码中怎么写的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: