Date类型接收空字符串(@InitBinder注解实现)

本文介绍了一种在Spring MVC框架中处理后端实体类Date类型字段接收到前端空字符串的方法,通过在Controller层使用@InitBinder注解及CustomDateEditor避免了数据转换错误。

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

当后端实体类中的属性为Date类型的数据接收前端传过来的数据为空字符串时,可能会报错(Failed to convert property value of type ‘java.lang.String’ to required type ‘java.util.Date’):
在这里插入图片描述
此时在不改变接收数据的实体类的情况下可以在控制层(Controller层)里添加如下代码:

@InitBinder
    protected void initDateFormatBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));//CustomDateEditor第二个参数传true表示运行传空字符串
    }

@InitBinder注解:
在使用SpringMVC框架的项目中,经常会出现遇到某些数据类型是Date、Integer、Double等的数据要绑定到控制器的实体,或者控制器需要接受这些数据,如果这类数据不做处理的话将无法绑定。
这里我们可以使用注解@InitBinder来解决这些问题,这样SpringMVC在绑定表单之前,都会先注册这些编译器。一般会将这些方法写在BaseController中,需要进行这类转换的控制器只需要继承BaseController即可。其实Spring提供了很多的实现类,如CustomDateEditor、CustomBooleanEditor、CustomNumberEditor等,基本上是够用的。

参考:
1、
https://blog.51cto.com/u_15704340/5442145
2、https://wenku.baidu.com/view/c6a61078383567ec102de2bd960590c69fc3d840.html?fr=sogou&wkts=1670480960708

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值