栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot 提交时间字符串报错 Failed to convert property value of type ‘java.lang.String‘ to required ‘Date‘

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot 提交时间字符串报错 Failed to convert property value of type ‘java.lang.String‘ to required ‘Date‘

Field error in object 'accountPeriod' on field 'endDate': rejected value [2021-12-31]; codes [typeMismatch.accountPeriod.endDate,typeMismatch.endDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [accountPeriod.endDate,endDate]; arguments []; default message [endDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'endDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@com.fasterxml.jackson.databind.annotation.JsonSerialize @javax.persistence.Temporal @javax.persistence.Column java.util.Date] for value '2021-12-31'; nested exception is java.lang.IllegalArgumentException]
Field error in object 'accountPeriod' on field 'startDate': rejected value [2021-12-11]; codes [typeMismatch.accountPeriod.startDate,typeMismatch.startDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [accountPeriod.startDate,startDate]; arguments []; default message [startDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'startDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@com.fasterxml.jackson.databind.annotation.JsonSerialize @javax.persistence.Temporal @javax.persistence.Column java.util.Date] for value '2021-12-11'; nested exception is java.lang.IllegalArgumentException]

  

解决方法:


第一方案:在实体类的属性上加上 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 注解。

如:  
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Column(name = "LOGIN_TIME")
private Date loginTime;

刚才发现,如果转换的时间格式定义为 "yyyy-MM-dd HH:mm:ss",

那页面传到后台的字符串是这种格式的:"2019-01-31 14:33",后台还是会报错,因为字符串里没有 秒 的数据。


第二个方案: 是在 controller 里加一个方法:

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(true);
        // true:允许输入空值,false:不能为空值
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }


如下图所示:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/658751.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号