Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date'

迷南。 2021-09-20 20:28 377阅读 0赞

这个bug涉及到一个比较重要的知识点,那就是SpringMVC框架中日期类型转换问题

bug描述:

Field error in object ‘product’ on field ‘departureTime’: rejected value [2019-10-15 05:50]; codes [typeMismatch.product.departureTime,typeMismatch.departureTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [product.departureTime,departureTime]; arguments []; default message [departureTime]]; default message [Failed to convert property value of type ‘java.lang.String’ to required type ‘java.util.Date’ for property ‘departureTime’; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value ‘2019-10-15 05:50’; nested exception is java.lang.IllegalArgumentException]

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L09uZV9MX1N0YXI_size_16_color_FFFFFF_t_70

bug分析:

这是因为在页面跳转的过程中,在页面上提交的数据是String类型,而在服务器中定义的是Date类型,类型不匹配所导致的错误,解决这个bug,就要用到SpringMVC中的日期类型转换,SpringMVC日期类型转换有三种方式,这里使用最简单的一种:注解(其他两种方式以后有时间补上)

bug消除:

实体类中加日期格式化注解

找到变量的实体类,在要进行类型转换的属性上面加上注解:@DateTimeFormat(pattern=”yyyy-MM-dd HH:mm”)

  1. @DateTimeFormat(pattern="yyyy-MM-dd HH:mm")
  2. private Date departureTime; // 出发时间

OK,bug解决

发表评论

表情:
评论列表 (有 0 条评论,377人围观)

还没有评论,来说两句吧...

相关阅读