springmvc時間類型值傳輸映射


背景: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 }

需要注意的是:

@dateTimeFormat是針對表單提交的情況可以使用,但是當前端使用json數據進行傳輸的時候就不行了

使用json數據傳輸時,我們常用的注解是@requestBody

此時需要使用@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8") 

此時就可以完美的映射時間字段了,使用了@jsonFormat注解的字段在前端顯示的時候,也會格式化輸出哦

解釋下timezone字段的意思:我們中國是東八區,需要加上8正確的顯示我們時區的時間

 

如果有不對,歡迎指正!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM