错误原因:
在项目中使用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