1
我想使用LocalDate
作爲spring-mvc
創建的Servlet
中的類型。 用戶應該能夠以多種有效格式提供日期yyyyMMdd, yyyy-MM-dd, yyMMdd, yy-MM-dd
。如何在spring mvc註冊LocalDate的全局數據綁定?
因此,我試圖爲該類註冊我自己的轉換器,在全球範圍內註冊它爲整個應用程序。但它從來沒有拿起
問題:我的自定義編輯器從來沒有被調用過。
@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
例外:
Parse attempt failed for value [2017-07-05]
調試過程中,我可以看到LocalDatePropertyEditor
類永遠不會被調用。但爲什麼?