2016-05-05 33 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

我看不出有办法做到这一点。可能有办法,但我不知道这一点。 –