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正确的显示我们时区的时间

如果有不对,欢迎指正!

原文地址:https://www.cnblogs.com/zfding/p/8322338.html