当后端实体类中的属性为Date类型的数据接收前端传过来的数据为空字符串时,可能会报错(Failed to convert property value of type ‘java.lang.String’ to required type ‘java.util.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表示运行传空字符串
}
@InitBinder注解:
在使用SpringMVC框架的项目中,经常会出现遇到某些数据类型是Date、Integer、Double等的数据要绑定到控制器的实体,或者控制器需要接受这些数据,如果这类数据不做处理的话将无法绑定。
这里我们可以使用注解@InitBinder来解决这些问题,这样SpringMVC在绑定表单之前,都会先注册这些编译器。一般会将这些方法写在BaseController中,需要进行这类转换的控制器只需要继承BaseController即可。其实Spring提供了很多的实现类,如CustomDateEditor、CustomBooleanEditor、CustomNumberEditor等,基本上是够用的。
参考:
1、
https://blog.51cto.com/u_15704340/5442145
2、https://wenku.baidu.com/view/c6a61078383567ec102de2bd960590c69fc3d840.html?fr=sogou&wkts=1670480960708