温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-07 20:08:39 来源:脚本之家 阅读:166 作者:smileNicky 栏目:编程语言

最近遇到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());
  }
}

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI