背景:SSM框架,mybatis逆向生成model实体以及mapper和sqlProvider作为DAO层,自行编写Controller和Service层以及用jsp作为View。
问题:jsp页面的input type="date"传给controller的数据库为date类型的字段出错。
页面报错:
控制台报错:
Field error in object ‘project’ on field ‘projectCreateTime’: rejected
value [2019-07-30]; codes
[typeMismatch.project.projectCreateTime,typeMismatch.projectCreateTime,typeMismatch.java.util.Date,typeMismatch];
arguments
[org.springframework.context.support.DefaultMessageSourceResolvable:
codes [project.projectCreateTime,projectCreateTime]; arguments [];
default message [projectCreateTime]]; default message [Failed to
convert property value of type ‘java.lang.String’ to required type
‘java.util.Date’ for property ‘projectCreateTime’; nested exception is
org.springframework.core.convert.ConversionFailedException: Failed
to convert from type [java.lang.String] to type [java.util.Date] for
value ‘2019-07-30’; nested exception is
java.lang.IllegalArgumentException]
错误: Failed to convert from type [java.lang.String] to type [java.util.Date]
解决途径:(选一种就能解决)
方法1:对象实体对应Date属性加上注解
@DateTimeFormat(pattern="yyyy-MM-dd")
方法2:在Controller里面添加下面代码(注意不要引错Date包)
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
@InitBinder
public void initBinder(WebDataBinder binder) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(true);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
=====================================================================
自己断断续续找了好几天都没有解决,问老师得到了思路。而且发现网上很多的方法都复杂而无效解决(emmmm),最后用上面那简短的代码/注解就完事了,激动。希望好而有效的教程越来越多。
听同学说好像前台input标签传过去的都是String类型,所以Date都要进行类型转换,自动注入可不帮做这件事情。但是网上有说input的date返回的是Date类型,经常百度找不到这些细节的答案(烦恼),是不是我太蠢了不会找资料。
唔,常做笔记是习惯。