栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

解决springmvc关于前台日期作为实体类对象参数类型转换错误的问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

解决springmvc关于前台日期作为实体类对象参数类型转换错误的问题

页面报错:

后台错误:

Field error in object 'user' on field 'birthday': rejected value [2013-06-24]; codes [typeMismatch.user.birthday,typeMismatch.birthday,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.birthday,birthday]; arguments []; default message [birthday]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'birthday'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.util.Date for value '2013-06-24'; nested exception is java.lang.IllegalArgumentException]

解决方案1:在对应的实体类属性上加入 @DateTimeFormat(pattern = "yyyy-MM-dd")

解决方案2:不使用 注解

使用 DefaultAnnotationHandlerMapping 和 AnnotationMethodHandlerAdapter 注解驱动配置

在对应的实体类属性上加入 @DateTimeFormat(pattern = "yyyy-MM-dd")


    
      
 
   
     
   
 
      
    

3、使用 @InitBinder注解,注册一个父类Controller(baseController),其他Controller去继承它

Springmvc配置文件 


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

或者使用下面的方式

public class baseController {
  @InitBinder
  public void initBinder(WebDataBinder binder) {
    
    binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {

      @Override
      public String getAsText() {
 return new SimpleDateFormat("yyyy-MM-dd")
     .format((Date) getValue());
      }

      @Override
      public void setAsText(String text) {
 try {
   setValue(new SimpleDateFormat("yyyy-MM-dd").parse(text));
 } catch (Exception e) {
   e.printStackTrace();
   setValue(null);
 }
      }

    });
  }
}

以上这篇解决springmvc关于前台日期作为实体类对象参数类型转换错误的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/145506.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号