2016-05-05 46 views
3

我希望我的controllers根據標準格式解析RequestParamsPathVariables中的日期。Spring MVC set global DateTimeFormat

是否可以設置應用程序範圍內的@DateTimeFormat而不分別註釋每個@RequestParam

回答

1

您可以在控制器級別執行此操作。在您的控制器中添加@initBinder,它會根據給定的格式化程序格式化日期。

@InitBinder 
public void initBinder(WebDataBinder binder) { 
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
    dateFormat.setLenient(false); 

    // true passed to CustomDateEditor constructor means convert empty String to null 
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); 
} 
+0

不是一部分,但是,有沒有辦法重寫此單個請求參數?當我使用InitBinder時,似乎DateTimeFormat會被忽略。 – Can

+0

我看不出有辦法做到這一點。可能有辦法,但我不知道這一點。 –