I'd like to use LocalDate
as type in a Servlet
created with spring-mvc
.
The users should be able to provide the date in multiple valid formats yyyyMMdd, yyyy-MM-dd, yyMMdd, yy-MM-dd
.
Therefor I'm trying to register my own converter for that class and register it globally for the whole application. But it is never picked up
Problem: my custom editor is never called.
@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) {
}
}
When calling:
localhost:8080/test?date=2017-07-05
Exception:
Parse attempt failed for value [2017-07-05]
During debug I can see the LocalDatePropertyEditor
class is never called. But why?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…