1. 程式人生 > >ssm後臺接收前臺Date型別引數格式的問題

ssm後臺接收前臺Date型別引數格式的問題

在使用springmvc @RequestBody來接收Date型別引數的時候,當格式不對的時候總會出現異常。給大家推薦幾種方法:

1.當你接收yyyy-MM-dd格式的日期時,只需要在實體類中相應的欄位上面加上@DateTimeFormat(pattern = “yyyy-MM-dd”)註解即可。

2.當你接收yyyy-MM-dd HH:mm:ss格式的日期時,用上面的方面就不行了,而且會報異常,因為上面的方法只是會轉換指定的幾種格式的Date型別,具體哪幾種格式可以檢視丟擲的異常,異常中有詳細的說明。

這時需要使用@JsonFormat(pattern=”yyyy-MM-dd HH:mm:ss”,timezone = “GMT+8”)註解了。這時就會自動轉換成該格式的註解。

3.最後這種方法,我試了不行,但是好多人說可以,不知道是怎麼弄的,在這裡也跟大家說說。就是在controller裡面中的一個方法加上@InitBinder註解,例子如下:

@InitBinder
 public void initBinder(WebDataBinder binder) {
  DateFormat sdf_yyyyMMdd_hhmmss = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
  sdf_yyyyMMdd_hhmmss.setLenient(false);

  binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf_yyyyMMdd_hhmmss, true));
  binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class,true));
  binder.registerCustomEditor(String.class,new StringTrimmerEditor(false));
  binder.registerCustomEditor(Long.class,new CustomNumberEditor(Long.class,true));
 }

我自己認為,如果是用@RequestBody來接收引數,這個方法不行,我試過的。這個方法會在到達Controller之前先呼叫,至於別人怎麼用的可以,我就不清楚了。總之第二種方法是既簡單,又方便。所以推薦使用第二種方法。

@DateTimeFormat(pattern="yyyy-MM-dd")        例如:2018-3-15

    private Date startTime;

 @JsonFormat(pattern="yyyy-MM-dd",timezone="GMT+8")   
    private Date updateTime;