SSM日期问题Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date'

背景: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类型,经常百度找不到这些细节的答案(烦恼),是不是我太蠢了不会找资料。

唔,常做笔记是习惯。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值