表单中字符串封装对象转换成Date出错

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值,获取到后,提交到后台,出现了上面的这一对异常信息。前端页面提交的时候参数检查了一下,看上去属性值都是对的,没什么问题。可是后端就是没法接收到参数。java

问题排查

去百度了一下上面的异常信息,得出的解决方法,方案以下后端

解决方案

在对应的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源码能够看到:ui

/**
 * 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,否则若是没有值,可能也报错了this

相关文章
相关标签/搜索