org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert val

本文介绍了在Spring MVC中遇到前端使用html date控件传参到后端Date类型字段时,引发的`MethodArgumentTypeMismatchException`异常。异常原因在于无法直接将String类型转换为Date类型。解决方法是后端使用String类型接收,再通过`SimpleDateFormat`解析转换为Date。详细步骤包括前端date控件设置和后端接收转换的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载请注明出处:https://blog.youkuaiyun.com/weixin_41459547/article/details/88845278

若有不对之处,感谢各位批评指导,希望大家一起讨论学习。

 

导读:第一部分为异常详情,第二部分为解决方法,若不想查看异常信息,可直接查看解决方法解决问题,

本文的背景:前端使用html的date控件,在后端使用Date类型字段接收时,发出错误,而String类型字段接收可以实现。具体实现方法为——通过SimpleDateFormat的parse方法将String类型转换为Date类型。

 

异常详情:


因异常代码量过长,所以放在文末,这里先贴出报错的那一整行的信息:

org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type [java.lang.String] to required type [java.util.Date]; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2000-09-24'; nested exception is java.lang.IllegalArgumentException


造成错误的原因在异常中已经说出来了,就是无法用Date类型数据接收String类型的数据,即无法发生转换,错误关键语句如下:
 

Failed to convert from type [java.lang.String] to type [java.util.Date]


然后,在发生类型转换的位置看下代码:

前端页面接收的部分,如下图,这里我们使用的类型type=date,所以我们接收的是一个date类型的数据:

<tr>
    <td>注册时间</td>
    <td><input id="jointimeTemp" name="jointimeTemp" type="date" value="2000-09-24"/></td>
</tr>


在后台,我的jointimeTemp字段是Date类型的数据,所以前端才设置为type=date类型。

然后我们在后台接收的方法头部分,我们接收jointimeTemp的类型为Date类型,想着跟前端部分的date类型对应

@RequestMapping("/managerAddStudent.action")
public @ResponseBody String managerAddStudent(Student student,Date jointimeTemp) {
    /*
        省略具体代码及返回值
    */
}


于是,这样配置之后,就爆出了Failed to convert from type [java.lang.String] to type [java.util.Date]的异常。

 

解决方法:


使用后端部分使用String类型字段接收前端的date类型的数据,代码如下;

@RequestMapping("/managerAddStudent.action")
public @ResponseBody String managerAddStudent(Student student,String jointimeTemp) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
    Date date = sdf.parse(jointimeTemp);   
    //SimpleDateFormat的parse方法是返回java.util.Date类型的数据
}


这样,就实现了使用html的date控件,然后在后端通过接收String类型字段,通过SimpleDateFormat的parse方法将String类型转换为Date类型。
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值