spring mvc使用过程中关于页面form绑定java.util.Date遇到的问题

最近在使用spring3.1的bind时候,遇到一个很蛋疼的错误,折腾了好久,记录与此,用于提醒自己.

页面form的时候date提交到controller的时候报错如下:
[com.dmx.controller.exception.resolver.SpringMvcHandlerExceptionResolver]org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'present' on field 'createTimeEnd': rejected value []; codes [typeMismatch.present.createTimeEnd,typeMismatch.createTimeEnd,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [present.createTimeEnd,createTimeEnd]; arguments []; default message [createTimeEnd]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'createTimeEnd'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'createTimeEnd': no matching editors or conversion strategy found]
Field error in object 'present' on field 'createTimeStart': rejected value []; codes [typeMismatch.present.createTimeStart,typeMismatch.createTimeStart,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [present.createTimeStart,createTimeStart]; arguments []; default message [createTimeStart]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'createTimeStart'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'createTimeStart': no matching editors or conversion strategy found]


查了很多资料,最后终于定位到问题:

重写controller里的initBinder方法,如下:

@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
// binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值