2013-03-01 32 views
83

我有一個GET請求,將YYYY-MM-DD格式的日期發送給Spring控制器。 控制器代碼如下:如何在Spring MVC控制器的GET請求中接受Date params?

@RequestMapping(value="/fetch" , method=RequestMethod.GET) 
    public @ResponseBody String fetchResult(@RequestParam("from") Date fromDate) { 
     //Content goes here 
    } 

該請求被正確地發送作爲我正在與螢火蟲檢查。 我得到的錯誤:

HTTP Status 400: The request sent by the client was syntactically incorrect.

我怎樣才能使控制器接受日期的格式? 請幫忙。我究竟做錯了什麼?

回答

170

好吧,我解決了它。 寫作它爲任何人在一整天的不間斷編碼&錯過這樣一個愚蠢的事情後可能會感到厭倦。

@RequestMapping(value="/fetch" , method=RequestMethod.GET) 
    public @ResponseBody String fetchResult(@RequestParam("from") @DateTimeFormat(pattern="yyyy-MM-dd") Date fromDate) { 
     //Content goes here 
    } 

是的,很簡單。只需添加DateTimeFormat註釋。

+15

我打算寫一個答案,但你打敗了我。您也可以使用@DateTimeFormat(iso = ISO.DATE),它是相同的格式。順便說一句,如果你能我建議你使用Joda DateTime庫。 Spring很好地支持它。 – Luciano 2013-03-01 19:06:55

+0

答案一般,但是!有沒有辦法將其配置爲Spring的默認值?把'@ DateTimeFormat'放在你有的每個控制器裏有點矯枉過正... – thorinkor 2016-12-09 12:23:51

+2

@Luciano當然你也可以做@DateTimeFormat(iso = ISO.DATE_TIME) – kiedysktos 2017-01-23 11:44:11

2

這是我做的,從前端

@RequestMapping(value = "/{dateString}", method = RequestMethod.GET) 
    @ResponseBody 
    public HttpStatus getSomething(@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String dateString) { 
    return OK; 
    } 

得到格式化的日期,您可以使用它來得到你想要的。

+2

沒有明白。如果您將日期字符串作爲字符串接收,而不是日期,那麼將@ DateTimeFormat添加到@ PathVariable有什麼意義? – 2017-11-27 16:13:15

相關問題