2017-07-05 27 views
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類永遠不會被調用。但爲什麼?

回答

1

我仍然不知道爲什麼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() 
     }); 
    } 
}