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