表单中字符串封装对象转换成Date出错
2016-12-01 00:00
232 查看
摘要: Cannot convert value of type no matching editors or conversion strategy found
这里说明一下,我们的项目后台使用的是Spring MVC。在前端有个页面里有一个简单的form表单查询功能,表单里面有一些日期字段的查询,该日期字段是My97获取到时间值得
注意这块的new CustomDateEditor(dateFormat, true)中的true,查看CustomDateEditor源码可以看到:
当allowEmpty字段为
所以这里最好是要设置一下为true,不然如果没有值,可能也报错了
default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'createDate'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'createDate': no matching editors or conversion strategy found]
这里说明一下,我们的项目后台使用的是Spring MVC。在前端有个页面里有一个简单的form表单查询功能,表单里面有一些日期字段的查询,该日期字段是My97获取到时间值得
问题分析
表单中有属性,值为My97 Date值,获取到后,提交到后台,出现了上面的这一对异常信息。前端页面提交的时候参数检查了一下,看上去属性值都是对的,没什么问题。但是后端就是无法接收到参数。问题排查
去百度了一下上面的异常信息,得出的解决方法,方案如下解决方案
在对应的controller中增加属性编辑器,也就是在对应的Controller类中加上这个方法就可以了@InitBinder protected void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); }
注意这块的new CustomDateEditor(dateFormat, true)中的true,查看CustomDateEditor源码可以看到:
/** * Create a new CustomDateEditor instance, using the given DateFormat * for parsing and rendering. * <p>The "allowEmpty" parameter states if an empty String should * be allowed for parsing, i.e. get interpreted as null value. * Otherwise, an IllegalArgumentException gets thrown in that case. * @param dateFormat DateFormat to use for parsing and rendering * @param allowEmpty if empty strings should be allowed */public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty) { this.dateFormat = dateFormat; this.allowEmpty = allowEmpty; this.exactDateLength = -1; }
当allowEmpty字段为
true的时候form表单传递的值可以为空。否则会出现
字符串解析为date报错。
所以这里最好是要设置一下为true,不然如果没有值,可能也报错了
相关文章推荐
- 将Fri May 04 17:25:34 CST 2012形式的日期字符串转换成java.util.Date对象的方法
- JavaScript Date toString 方法:将 Date 对象转换为字符串
- Javascript:日期字符串(DateStr)与日期对象(Date)之间的转换
- JavaScript中扩展字符串与Date对象之间的转换,支持大多数日期格式的字符串(包括中文)
- JavaScript中扩展字符串与Date对象之间的转换,支持大多数日期格式的字符串(包括中文)
- 将Fri May 04 17:25:34 CST 2012形式的日期字符串转换成java.util.Date对象的方法
- javascript中日期(Date)字符串转换为日期(Date)对象
- 使用JSON.parse将json字符串转换成json对象的时候会出错
- 特殊字符导致json字符串转换成json对象出错
- 2014-12-03:hibernate get()与load()区别,json字符串转换为json对象,String与date相互转换
- javascript转换日期字符串为Date对象
- 【JAVA学习】java基本数据类型与字符串之间的转换(基本数据类型、对象封装类、自动装箱、自动拆箱)
- javascript中验证日期(Date)字符串转换为日期(Date)对象的不同情况结果
- Javascript:日期字符串(DateStr)与日期对象(Date)之间的转换
- javascript日期字符串转换为Date对象
- javascript中如何正确将日期(Date)字符串,转换为日期(Date)对象?
- javascript转换日期字符串---转化为Date对象---再转化为时间戳
- js动态获取当前系统时间+js字符串转换为date日期对象
- JavaScript中扩展字符串与Date对象之间的转换,支持大多数日期格式的字符串(包括中文)
- json里的日期字符串 怎么 转换成 javascript 的 Date 对象?