直接上问题: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)); } }