原文: http://www.cnblogs.com/rollenholt/p/3890415.html ------------------------------------------- bean里类型是Date,页面输入2015-10-01,无法转换为Date类型。
相应的解决办法为:
在对应的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报错。
|