项目场景:
在做一个导出功能时,要求根据查询条件导出,但是在接收Date类型时错误
问题描述
在做一个导出功能时,要求根据查询条件导出,但是在接收Date类型时错误
Field error in object 'informationSharingReq' on field 'reportEndTime': rejected value [2022-08-23]; codes [typeMismatch.informationSharingReq.reportEndTime,typeMismatch.reportEndTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [informationSharingReq.reportEndTime,reportEndTime]; arguments []; default message [reportEndTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'reportEndTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@io.swagger.annotations.ApiModelProperty java.util.Date] for value '2022-08-23'; nested exception is java.lang.IllegalArgumentException]
原因分析:
主要是因为前端传的是String,后台接受的是Date,类型不正常接受不了
解决方案:
前端的格式
两种解决方案
一、在字段上加一个 @DateTimeFormat(pattern = “yyyy-MM-dd”)注解
二、在controller方法里面加@InitBinder注解修饰的方法
注意:前端是什么格式后端就是什么格式
这个@InitBinder注解修饰的方法,在你每次进入controller之前都会对yyyy-MM-dd类型的参数转换成Date,当然我们还可以在这个方法做一些其他的操作,根据实际业务来
@RequestMapping(path = "/exportAllSharingList", method = RequestMethod.GET, produces = {
"application/json;charset=UTF-8"})
public void exportAllSharingList(HttpServletResponse response, String token,InformationSharingReq req) {
sharing.exportAllSharingList(response, token,req);
}
@InitBinder
public void initBinder(WebDataBinder binder, WebRequest request) {
//转换日期 注意这里的转化要和传进来的字符串的格式一直 如2015-9-9 就应该为yyyy-MM-dd
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
}
版权声明:本文为xiaobaixuedaima原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。