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、前端传递正确的日期/不传递该参数

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值