SpringBoot提交日期参数失败的解决方法
前端或移动端向后台传递参数时,时间类型的参数通常会从转换成String类型来进行传递,而后台实体中对应的数据类型是Date类型就会发生强转异常。
@Configuration
public class FastJsonConfiguration {
@Autowired
private RequestMappingHandlerAdapter handlerAdapter;
@PostConstruct // @PostContruct是spring框架的注解,在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化的时候执行该方法。
public void initEditableValidation() {
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer();
if (initializer.getConversionService() != null) {
GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService();
// 将自定义得字符串转日期实现类交给springboot 处理
genericConversionService.addConverter(new StringToDateConverter());
}
}
}
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 dateTimeFormat = "HH:mm:ss";
@Override
public Date convert(String source) {
if (StrUtil.isBlank(source) || StrUtil.equalsIgnoreCase("undefined", source) || StrUtil.equalsIgnoreCase("null", 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(":")){
formatter = new SimpleDateFormat(dateTimeFormat);
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));
}
}
这样便会先将String类型的日期数据先转化为Date类型的数据,在装进实体中便不会报错了
以上是 SpringBoot提交日期参数失败的解决方法 的全部内容, 来源链接: utcz.com/z/512747.html