当前位置:   article > 正文

java中接收java.util.Date类型的参数,报错Can not deserialize value of type java.util.Date from String_cannot deserialize value of type `java.util.date`

cannot deserialize value of type `java.util.date` from string

1. 问题

SpringBoot工程(其实跟SpringBoot没有关系),在controller中指定了接收参数类型为java.util.Date,但是前端不管是发来日期字符串还是时间戳,都报错Failed to convert property value of type java.lang.String to required Date

2. 原因分析

SpringMVC不能自动转换日期字符串或者时间戳java.util.Date

3. 解决方法

3.1 方法1

Spring有一个日期转换注解@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")可以在接口中将字符串类型参数yyyy-MM-dd HH:mm:ss转换为java.util.Date。举例:

 

  1. //这是接口使用的参数类
  2. public class Test {
  3. @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  4. private Date startTime;
  5. @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  6. private Date endTime;
  7. public Date getStartTime() {
  8. return startTime;
  9. }
  10. public void setStartTime(Date startTime) {
  11. this.startTime = startTime;
  12. }
  13. public Date getEndTime() {
  14. return endTime;
  15. }
  16. public void setEndTime(Date endTime) {
  17. this.endTime = endTime;
  18. }
  19. }

 

  1. // 使用上面参数类的接口
  2. public class TestController {
  3. @RequestMapping(value = "/ask",method = RequestMethod.POST)
  4. public void testMethod(Test test) {
  5. // do something
  6. }
  7. }

3.2 方法2

在controller中添加一个方法,这个方法为当前接口的所有方法处理Date类型转换。

 

  1. // 使用上面参数类的接口
  2. public class TestController {
  3. // 增加的方法
  4. @InitBinder
  5. protected void init(HttpServletRequest request, ServletRequestDataBinder binder) {
  6. SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss" );
  7. dateFormat.setLenient(false); //是否严格解析时间 false则严格解析 true宽松解析
  8. binder.registerCustomEditor( Date.class, new CustomDateEditor(dateFormat, false));
  9. }
  10. @RequestMapping(value = "/ask",method = RequestMethod.POST)
  11. public void testMethod(Test test) {
  12. // do something
  13. }
  14. }

实际上,这里不仅仅可以来处理时间类型,还可以来处理其它的数据类型(非基本类型数据)如CustomDateEditor、CustomBooleanEditor、CustomNumberEditor等。
如果嫌弃在每个controller中添加这个方法不方便管理,还可以使用Spring AOP功能,新建一个类。

 

  1. @ControllerAdvice
  2. public class DateHandler {
  3. @InitBinder
  4. public void initBinder(WebDataBinder binder) {
  5. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  6. dateFormat.setLenient(false); //是否严格解析时间 false则严格解析 true宽松解析
  7. binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
  8. }
  9. }

这个切面方法会为每一个controller处理日期转换。


参考文章:
作者:猫仙草
链接:https://www.jianshu.com/p/cb108ecbec89

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/813806
推荐阅读
相关标签
  

闽ICP备14008679号