轉自:https://www.cnblogs.com/liaojie970/p/5566388.htmlhtml
在使用spring mvc中,綁定頁面傳遞時間字符串數據給Date類型是出錯:java
Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for property 'expert.birthdate'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'birthdate': no matching editors or conversion strategy found spring
解決方法一:mvc
1.使對應Controller控制器繼承 extends SimpleFormController
2.重寫initBinder方法 ui
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder){ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); }
注意SimpleDateFormat日期格式與頁面日期格式要一致!spa
解決方法二:code
Spring3.0以上的SimpleFormController 已通過時了,最新方式是使用@InitBinder註解的方式orm
在對應的Controller控制器中htm
@InitBinder protected void init(HttpServletRequest request, ServletRequestDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); }