1. 程式人生 > >springmvc-前臺傳遞時間類型到後臺報錯

springmvc-前臺傳遞時間類型到後臺報錯

rop ram 前臺 blog sage bmi ont frame cer

背景:springmvc4.3.2+spring4.3.2+mybatis3.4.1

當前臺傳遞的參數有時間類型時,封裝的vo對象也有對應的時間類型與之對象,

但是如果此時用對象去接收後臺會報錯,類型轉換異常。

例子:

1 @RequestMapping("/test5")
2     public String test5(ResultInfo result){
3         Date birthday = result.getBirthday();
4         System.out.println(birthday);
5         System.out.println(result);
6 return "success"; 7 }
1 <form action="json/test5" method="post">
2         <input type="date" name="birthday" id="birthday"/>
3         <input type="text" name="code" />
4         <input type="text" name="desc" />
5         <input type="submit" value="提交" />
6
</form>

報錯如下:

Field error in object ‘resultInfo‘ on field ‘birthday‘: rejected value [2018-01-02]; 
codes [typeMismatch.resultInfo.birthday,typeMismatch.birthday,typeMismatch.java.util.Date,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [resultInfo.birthday,birthday];
arguments []; default message [birthday]]; default message [Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for property ‘birthday‘;
nested exception is org.springframework.core.convert.ConversionFailedException:
Failed to convert from type [java.lang.String] to type [java.util.Date] for value ‘2018-01-02‘; nested exception is java.lang.IllegalArgumentException]

看這紅色的部分知道,消息轉換器不能將字符串轉換為時間類型的數據。需要我們手動的去轉換。

我們只需要在vo(ResultInfo )對象的時間類型的屬相加上@DateTimeFormat(pattern="yyyy-mm-dd") 就可以啦

 1 public class ResultInfo implements Serializable{
 2 
 3     private static final long serialVersionUID = 1L;
 4     
 5     private String code ;
 6     private String desc;
 7     private Object data;
 8     //解決後臺類型為時間類型無法轉換的問題
 9     @DateTimeFormat(pattern="yyyy-mm-dd")
10     private Date birthday;
11 }

springmvc-前臺傳遞時間類型到後臺報錯