SpringBoot传递带有Date类型参数失败解决办法

在Vue和SpringBoot项目中遇到前端日期参数无法自动绑定到后台实体类Date类型的问题。通过添加一个自定义的StringToDateConverter配置类,实现了日期字符串到Date的转换,解决了参数传递失败的错误。配置类根据日期格式解析字符串,确保了前端和后台的数据交互正常。
摘要由CSDN通过智能技术生成

错误原因:

在项目中使用Vue+SpringBoot框架进行开发,当前台传递的参数中有对应后台实体类的Date时间类型的时候,SpringBoot会自动绑定失败

Vue前端代码:
使用的element ui框架写的表单:

<el-col :span="12">
 <el-form-item label="成立时间" prop="estaTime" label-width="130px">
    <el-date-picker
      v-model="enterprise.estaTime"
      type="date"
      value-format="yyyy-MM-dd"
      placeholder="选择日期">
    </el-date-picker>
  </el-form-item>
</el-col>

页面效果:
在这里插入图片描述
其中,value-format=“yyyy-MM-dd” 进行时间格式化,如果不加,则默认时间为格林威治时间格式,请注意
提交表单代码如下:

submit('save', this.enterprise).then(res => {
  if (res.data.success) {
    this.formVisible = false;
    this.$message({
      type: 'success',
      message: '操作成功!'
    })
    bus.$emit('toCompanyTable', true);
  } else {
    this.$message({
      type: 'error',
      message: res.data.msg
    })
  }
})

在往后台提交时,结果提示错误
在这里插入图片描述
解决办法:
写一个配置类,使用@Configuration注解交给SpringBoot进行管理:

package org.springblade.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.Date;

@Configuration
public class StringToDateConverter implements Converter<String, Date> {
	private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
	private static final String shortDateFormat = "yyyy-MM-dd";
	private static final String dateFormat2 = "yyyy/MM/dd HH:mm:ss";
	private static final String shortDateFormat2 = "yyyy/MM/dd";

	@Override
	public Date convert(String source) {
		if (StringUtils.isBlank(source)) {
			return null;
		}
		source = source.trim();
		try {
			SimpleDateFormat formatter;
			if (source.contains("-")) {
				if (source.contains(":")) {
					formatter = new SimpleDateFormat(dateFormat);
				} else {
					formatter = new SimpleDateFormat(shortDateFormat);
				}
				Date dtDate = formatter.parse(source);
				return dtDate;
			} else if (source.contains("/")) {
				if (source.contains(":")) {
					formatter = new SimpleDateFormat(dateFormat2);
				} else {
					formatter = new SimpleDateFormat(shortDateFormat2);
				}
				Date dtDate = formatter.parse(source);
				return dtDate;
			}
		} catch (Exception e) {
			throw new RuntimeException(String.format("parser %s to Date fail", source));
		}

		throw new RuntimeException(String.format("parser %s to Date fail", source));

	}
}

StringUtils为apache lang3包

重启项目,问题解决,参数传递成功!

以此记载,谨防忘记!

转载自:https://blog.csdn.net/weixin_39270764/article/details/81808152

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值