Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date'

本文介绍了解决前端使用Element的DatePicker组件传递日期到后端时出现的类型转换错误的方法。通过在Controller中使用@InitBinder注解,自定义了String到Date类型的转换,确保了日期数据的正确传递。

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

一、序言

在前端使用element的DatePicker 组件时,向后端传递如“2020-4-19”到后端,后端采用封装的实体类接收,类型为Date,此时就出现了如下错误

Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'endPublishingDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String

二、解决方法

利用@InitBinder,他是一个作用于Controller的初始化,功能之一就是可以将一些数据转换为我们需要的数据类型,这里就是利用这点,由于它是作用于Controller,所以一下代码时需要放置在controller中,如果需要全局,则一般配置在顶层的BaseController之中

在这里插入图片描述

 	/**
     * 将前台传递过来的日期格式的字符串,自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder)
    {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
        {
            @Override
            public void setAsText(String text)
            {
            	if(StrUtil.isNotEmpty(text)){
            		// text 不为空,则将其转换为 Date
            		setValue(DateUtils.parseDate(text));
            	}eles{
            		// 为空即将设置为null
          			setValue(null);
            	}
            }
        });
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值