AJAX请求400,类型转换异常ConversionFailedException

2022-07-18

  • 问题:前端发送ajax请求,http响应码400,后端tomcat服务报ConversionFailedException: Failed to convert from type [java.lang. String] to type [java.util. Date]

  • 原因:某个字段前端传递的类型是String,而后端接收的是Date类型,类型转换错误

  • 解决:

    • 方案一:在Controller控制层中,添加如下代码

      @InitBinder
      public void initBinder(WebDataBinder binder) {
      	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      	sdf.setLenient(false);
      	binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
      }
      

      需要导入

      import org.springframework.web.bind.WebDataBinder;
      import org.springframework.web.bind.annotation.InitBinder;
      import org.springframework.beans.propertyeditors.CustomDateEditor;
      
    • 方案二:在实体类对象字段上添加@JsonFormat注解

      @JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
      private Date requireDate;
      
      • @JsonFormat不仅可以完成后台到前台参数传递的类型转换,还可以实现前台到后台类型转换
      • @DateFormat这个是用于将前台传到后台字符串变量转换为Date类型
posted @ 2022-07-18 14:28  江亭夕望  阅读(321)  评论(0)    收藏  举报