zoukankan      html  css  js  c++  java
  • SpringMVC日期类型接收空值异常问题

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

    在这里插入图片描述

  • 相关阅读:
    Springboot 连接数据库
    线程专题 -- 线程的创建,状态,工作过程,常见方法
    MySQL中UPDATE语句里SET后使用AND的执行过程和结果分析
    SpringCloud | 通过电商业务场景让你彻底明白SpringCloud核心组件的底层原理
    避坑 | Java8使用并行流(ParallelStream)注意事项
    Spring--AOP、通知的执行顺序
    JVM--理解介绍
    JSF学习实战
    策略模式--实战1
    二叉树、二叉查找树、平衡树和红黑树概念
  • 原文地址:https://www.cnblogs.com/mzq123/p/11747829.html
Copyright © 2011-2022 走看看