org.springframework.validation.BindException:
Failed to convert from type [java.lang.String] to type [@io.swagger.annotations.ApiModelProperty java.sql.Date] for value '';
nested exception is java.lang.IllegalArgumentException
一、关于接收前端传递的日期参数的问题:
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd")// 空字符串时sql.Date解析报错
@DateTimeFormat(pattern = "yyyy-MM-dd")// 该注解仅对Util.Date类型有效,sql.Date类型解析报错
@JSONField(format = "yyyy-MM-dd")// 空字符串时sql.Date解析报错
1、直接使用sql.Date类型接收时,空字符串解析报错,无法自动映射为null,需要自定义解析
二、方案:
1、Controller层添加以下方法,自定义解析参数(只在该Controller层生效,可以另写一个类,其它类继承它)
@InitBinder
public void initBinder(WebDataBinder binder){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new PropertyEditorSupport(){
/**
* Sets the property value by parsing a given String. May raise
* java.lang.IllegalArgumentException if either the String is
* badly formatted or if this kind of property can't be expressed
* as text.
*
* @param text The string to be parsed.
*/
@Override
public void setAsText(String text) throws IllegalArgumentException {
try{
// 空字符串时直接返回null
if(StrUtil.isEmpty(text)){
setValue(null);
return;
}
// 先转成java.util.Date,获取毫秒数再转换成sql.Date
java.util.Date utilDate = simpleDateFormat.parse(text);
setValue(new Date(utilDate.getTime()));
}catch (Exception ex){
throw new GisBootException("sqlDate日期解析错误");
}
}
});
}
2、使用java.util.date接收参数,在用于查询时格式化为yyyy-MM-dd