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类型

__EOF__

本文作者江亭夕望
本文链接https://www.cnblogs.com/jtxw/p/16490295.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   江亭夕望  阅读(295)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示