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

关于springmvc日期问题的解决方式 除了本博客的【springMVC 前后台日期格式传值解决方式之 @DateTimeFormat的使用和配置】一文,

还有如下这种方式:

在Controller里加上这段代码:

 1     @InitBinder
 2     public void initBinder(ServletRequestDataBinder binder) {
 3         /**
 4          * 自动转换日期类型的字段格式
 5          */
 6         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 7         binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
 8 
 9         
10     }

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

 1     @InitBinder
 2     public void initBinder(ServletRequestDataBinder binder) {
 3         /**
 4          * 自动转换日期类型的字段格式
 5          */
 6         SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
 7         SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月");
 8         try {
 9             binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf2, true));
10         }catch(Exception e) {
11             binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf1, true));
12         }
13         
14     }

 

怎么解决呢?

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

 

原文内容如下

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

配置文件为

1
2
3
4
5
< bean  class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >  
     < property  name = "webBindingInitializer" >  
         < bean  class = "xx.xxx.MyBindingInitializer" />  
     </ property >  
</ bean



MyBindingInitializer中,initBinder方法里的
binder.registerCustomEditor(Date.class, new XXXEditor());


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

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

 

至于其中的XXXEditor怎么写,大家可以参照例子中的CustomDateEditor,即:org.springframework.beans.propertyeditors.CustomDateEditor源码中怎么写的。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值