直接上問題:java
Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Timestamp' for property 'sale_time'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.sql.Timestamp for value ''; nested exception is java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]] spring
異常緣由:sql
後臺bean的屬性有Timestamp類型的屬性,頁面表單中日後臺傳輸的時候是以字符串傳遞的。mvc
spring mvc在自動轉換屬性類型的時候,若是頁面對應bean屬性的值傳遞格式不正確(如:Timestamp類型,傳遞空串,則報以上異常)ide
解決辦法:ui
重寫spring自帶的CustomDateEditor類的setAsText(String text)方法邏輯;this
/** * All Right Reserved, Copyright (C) 2015, dengjie, Ltd.<br/> * 自定義日期格式解析器 * @author dengjie created at 2015-11-19 下午8:28:09 */ public class CDateEditor extends CustomDateEditor { private DateFormat dateFormat; private int exactDateLength = -1; private final boolean allowEmpty; public CDateEditor(DateFormat dateFormat, boolean allowEmpty) { super(dateFormat, allowEmpty); this.dateFormat = dateFormat; this.allowEmpty = allowEmpty; } @Override public void setAsText(String text) throws IllegalArgumentException { /* * 判斷是否是空串,此處也能夠判斷格式是否正確 */ if (text.replaceAll("\\s", "").length() == 0) { // Treat empty String as null value. setValue(null); } else if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) { throw new IllegalArgumentException( "Could not parse date: it is not exactly" + this.exactDateLength + "characters long"); } else { try { setValue(this.dateFormat.parse(text)); } catch (ParseException ex) { throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex); } } } @Override public String getAsText() { return getValue().toString(); } }
使用:spa
/** * 其餘的Controller繼承該Controller或者在指定的Controller中使用@InitBinder * Created by dengjie on 2015/11/01. */ @Controller public class BaseController { @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormat.setLenient(false); // 參數2是否容許爲空 binder.registerCustomEditor(Timestamp.class, new CDateEditor(dateFormat, false)); } }