我想在使用 spring-mvc
创建的 Servlet
中使用 LocalDate
作为类型。
用户应该能够以多种有效格式提供日期 yyyyMMdd、yyyy-MM-dd、yyMMdd、yy-MM-dd
。
因此,我正在尝试为该类注册我自己的转换器,并为整个应用程序全局注册。但它从未被捡起
问题:从未调用我的自定义编辑器。
@Bean
public CustomEditorConfigurer init() {
CustomEditorConfigurer c = new CustomEditorConfigurer();
c.setPropertyEditorRegistrars(new PropertyEditorRegistrar[] {
(registry) -> registry.registerCustomEditor(LocalDate.class, new LocalDatePropertyEditor())
});
return c;
}
public class LocalDatePropertyEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) {
this.setValue(LocalDate.parse(text, DateTimeFormatter.ISO_DATE));
}
@Override
public String getAsText() {
return this.getValue().toString();
}
}
@RestController
public void DateServlet {
@RequestMapping("/test")
public void test(@RequestParam LocalDate date) {
}
}
调用时:
localhost:8080/test?date=2017-07-05
Exception:
Parse attempt failed for value [2017-07-05]
在调试期间,我可以看到 LocalDatePropertyEditor
类从未被调用。但是为什么?
最佳答案
我仍然不知道为什么 PropertyEditor
不起作用。
但以下解决方案有效。
@Configuration
public class LocalDateConfig extends WebMvcConfigurerAdapter {
@Override
public void addFormatters(FormatterRegistry registry) {
super.addFormatters(registry);
registry.addFormatterForFieldType(LocalDate.class, new Formatter<LocalDate>() {
//override parse() and print()
});
}
}
关于java - 如何在 spring mvc 中为 LocalDate 注册全局数据绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44924656/