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

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

2013-05-15 19:35 513 查看
最近在使用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));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: