欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

SpringMVC日期类型接收空值异常问题解决方法

时间:2021-08-08 08:25:13|栏目:JAVA代码|点击:

最近遇到SpringMVC写个controller类,传一个空串的字符类型过来,正常情况是会自动转成date类型的,因为数据表对应类类型就是date的

解决方法是在controller类的后面加个注解:

@InitBinder
  protected void initDateFormatBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
  }

注意,上面的代码CustomDateEditor构造函数要传个true参数,表示允许传空字符串来进行日期类型转换

CustomDateEditor 里源码

public class CustomDateEditor extends PropertyEditorSupport {
  private final DateFormat dateFormat;
  private final boolean allowEmpty;
  private final int exactDateLength;

  public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty) {
    this.dateFormat = dateFormat;
    this.allowEmpty = allowEmpty;
    this.exactDateLength = -1;
  }
  ....
}

Spring Bean类的装载是通过BeanWrapperImpl来实现,可以写个简单的例子,验证这个问题,DispatchInfoModel 类是我自己的测试类,里面有signDate这个date类型的参数

设置为true的情况,是可以正常运行的

public class mytest {
  public static void main(String[] args) {
    DispatchInfoModel tm = new DispatchInfoModel();
    BeanWrapper bw = new BeanWrapperImpl(tm);
    bw.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    bw.setPropertyValue("signDate", "");
    System.out.println(tm.getSignDate());
  }
}

设置为false的情况,会抛出异常:

public class mytest {
  public static void main(String[] args) {
    DispatchInfoModel tm = new DispatchInfoModel();
    BeanWrapper bw = new BeanWrapperImpl(tm);
    bw.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
    bw.setPropertyValue("signDate", "");
    System.out.println(tm.getSignDate());
  }
}

上一篇:IDEA 打开java文件对应的class路径的操作步骤

栏    目:JAVA代码

下一篇:Eclipse 开发java 出现Failed to create the Java Virtual Machine错误解决办法

本文标题:SpringMVC日期类型接收空值异常问题解决方法

本文地址:http://www.codeinn.net/misctech/165093.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有