直接在controller中用Date类型接受传过来的日期是会报错的。
@RequestMapping("/test") public String test(Date date){ return "hello example"; }
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'orderDTO' on field 'orderDate': rejected value [2017-09-14]; codes [typeMismatch.orderDTO.orderDate,typeMismatch.orderDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [orderDTO.orderDate,orderDate]; arguments []; default message [orderDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'orderDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.util.Date for value '2017-09-14'; nested exception is java.lang.IllegalArgumentException]
解决方法很简单:
第一步:在接受的参数上加日期格式注解
@DateTimeFormat(pattern="yyyy-MM-dd") private Date orderDate;
当然有可能你是直接在controller中用变量接受的,也是可以加注解的,而不是和我一样用一个dto类接受所有参数也是一样加上这个注解
第二步:maven添加jar包
<dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.9.4</version> </dependency>