java - Spring从请求中自动转换LocalDate
问题描述
Spring(4.3)是否有可能自动将我的自定义日期转换为 LocalDate 格式?
我有一个简单的请求方法(我不知道它是如何真正调用的):ResponseEntity<?> placeOrder(@RequestBody PlaceOrderForm form);
这是我的 PlaceOrderForm:
public class PlaceOrderForm {
private LocalDate deliveryDate;
public LocalDate getDeliveryDate() {
return deliveryDate;
}
public void setDeliveryDate(LocalDate deliveryDate) {
this.deliveryDate = deliveryDate;
}
}
我读到了一个自定义转换器......我创建了一个:
@Component
public class StringToLocalDateConverter implements Converter<String, LocalDate> {
@Override
public LocalDate convert(String source) {
String format = messageSource.getMessage("text.store.dateformat", null, i18nService.getCurrentLocale());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return LocalDate.parse(source, formatter);
}
}
我还读到我需要告诉 ConversionService,我有一个新的转换器:
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list merge="true">
<bean id="stringToLocalDateConverter" class="de.test.converter.StringToLocalDateConverter" />
</list>
</property>
</bean>
但这一切都无济于事,我收到以下错误:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of java.time.LocalDate (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('10.10.2019'); nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of java.time.LocalDate (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('10.10.2019')
有人可以告诉我我做错了什么吗?
解决方案
在类 PlaceOrderForm 中使用注释,如下所示,并在使用时@RequestBody PlaceOrderForm form
添加默认构造函数
public class PlaceOrderForm {
@DateTimeFormat(pattern = "dd.MM.yyyy")
private LocalDate deliveryDate;
public PlaceOrderForm(){}
@controller
在类中添加以下方法
@InitBinder
public void initBinder(final WebDataBinder binder) {
final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
推荐阅读
- google-apps-script - 运行包含 If 语句的应用程序脚本代码(如何自动触发?) - Google Apps 脚本/Google 表格
- r - R:动态拆分数据帧
- android - 如何通过在 Android 中拖动来在屏幕上移动对象?
- spring - spring jms - 在收到消息之前执行操作
- laravel - Laravel 导入问题
- bash - 双引号bash脚本中的双引号
- ios - 时区名称/偏移量的缩写
- python - 在 Python 中使用 MySQL 连接器出现“客户端不支持服务器请求的身份验证协议”的错误
- semantic-ui - Svelte 应用程序在运行项目时返回“意外字符@”错误
- ionic-framework - Ionic 4:正确设置本机 http 帖子标头