关于SpringBoot使用实体接收GET请求,时间参数转换报错问题

笔者所在公司框架采用的是前后端分离,原先后端接收前端的GET查询请求,使用@RequestParam Map params的方式进行接收,如下:

@ApiOperation("分页查询数据变更记录") @GetMapping("/list") public Result> list(@ApiParam("请求参数") @RequestParam Map params) {

现改成
@ApiOperation("分页查询数据变更记录") @GetMapping("/list") public Result> list(@ApiParam("请求参数") DataRevision dataRevision) {

在发起交易测试,发现除了时间类型的字段转换会报错,其他类型SpringBoot可正常进行转换,
请求地址:http://localhost:8088/data-re...
报错信息:
org.springframework.validation.BeanPropertyBindingResult: 1 errors\nField error in object 'dataRevision' on field 'startDate': rejected value [2022-05-13T00:00:00 08:00]; codes [typeMismatch.dataRevision.startDate,typeMismatch.startDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [dataRevision.startDate,startDate]; arguments []; default message [startDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'startDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@com.baomidou.mybatisplus.annotation.TableField java.util.Date] for value '2022-05-13T00:00:00 08:00'; nested exception is java.lang.IllegalArgumentException]
【关于SpringBoot使用实体接收GET请求,时间参数转换报错问题】对故障分析,由上可看出将2022-05-13T00:00:00+08:00转换成java.util.Date类型时出现异常。通过排查网上的相关材料,需要对Controller请求进行全局的拦截,从而实现对绑定变量的值处理:
import cn.hutool.core.date.DateUtil;
@Slf4j
@ControllerAdvice
@RefreshScope
public class GlobalControllerAdvice {
@InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { try { //将前端上送的时间进行格式化,如:2022-05-13T00:00:00 08:00格式化成2022-05-13T00:00:00+08:00 String realText = text.replace(" ", "+"); setValue(DateUtil.parseUTC(realText)); } catch (Exception e) { log.error("绑定变量转换值异常:" + e.getMessage(), e); setValue(DateUtil.parse(text)); } } }); }

    推荐阅读