1. 程式人生 > >spring mvc使用GET請求獲取Date型別的方法

spring mvc使用GET請求獲取Date型別的方法

最近在專案是使用GET進行請求,且後臺接收引數的型別為Date出現為null的情況,經過在網上查找了下可以在接收引數的欄位使用@DateTimeFormat這一註解來解決問題。

例如:

@RequestMapping(value="/fetch" , method=RequestMethod.GET)
public @ResponseBody String fetchResult(@RequestParam("from") Date fromDate) {
        //Content goes here
    }
這裡 fromDate在後端列印顯示是null,如果改為下面的方式處理
@RequestMapping(value="/fetch" , method=RequestMethod.GET)
public @ResponseBody String fetchResult(@RequestParam("from") @DateTimeFormat(pattern="yyyy-MM-dd") Date fromDate) {
     //Content goes here
 }

通過@DateTimeFormat這個日期格式化註解,就可以將前端傳入的字串格式化為日期型別可以識別的內容資訊了。當然也可以使用@DateTimeFormat(iso=ISO.DATE)這樣子的格式化來進行處理,效果是一樣的。