java后端接收前端传递的日期参数为空字符串时报错
一、关于接收前端传递的日期参数的问题:
前提:
Date类型的属性上添加了以下注解:
(图片来源网络,侵删)
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd") @DateTimeFormat(pattern = "yyyy-MM-dd") @JSONField(format = "yyyy-MM-dd")
1、java.sql.date:空字符串解析报错,正常日期格式字符串没问题;
2、java.util.date:空字符串解析没问题,正常日期格式字符串用于查询时报错;
二、方案:
1、Controller层添加以下方法,自定义解析参数(只在该Controller层生效)
@InitBinder public void initBinder(WebDataBinder binder){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); // spring提供的日期解析器(格式化,是否允许为空)选择true则将空字符串解析为null CustomDateEditor customDateEditor = new CustomDateEditor(simpleDateFormat, true); // 为Date类型的属性注册解析器 binder.registerCustomEditor(Date.class, customDateEditor); }
2、java.util.date用于查询时格式化为yyyy-MM-dd
3、前端传递正确的日期/不传递该参数
(图片来源网络,侵删)
(图片来源网络,侵删)
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。
还没有评论,来说两句吧...