SpringMVC系列之日期类型接收空值异常

Bertha 。 2021-08-13 23:52 276阅读 0赞

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

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

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

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

CustomDateEditor 里源码

  1. public class CustomDateEditor extends PropertyEditorSupport {
  2. private final DateFormat dateFormat;
  3. private final boolean allowEmpty;
  4. private final int exactDateLength;
  5. public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty) {
  6. this.dateFormat = dateFormat;
  7. this.allowEmpty = allowEmpty;
  8. this.exactDateLength = -1;
  9. }
  10. ....
  11. }

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

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

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

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

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

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,276人围观)

还没有评论,来说两句吧...

相关阅读