-
当controller中的方法直接用参数接收前端传递的参数时
日期格式不匹配会报如下错误:Failed to convert value of type 'java.lang.String' to required type 'java.util.Date';,就是说类型转换异常
@PostMapping("/1") public String doSign1(Long userId, Date signDate){ System.out.println("userId:" + userId); System.out.println("date:" + signDate); return "123"; }
解决方法就是给controller方法的参数加上日期格式化注解
@DateTimeFormat
@PostMapping("/1") public String doSign1(Long userId, @DateTimeFormat(pattern = "yyyy-MM-dd") Date signDate){ System.out.println("userId:" + userId); System.out.println("date:" + signDate); return "123"; }
-
当controller中的方法用实体类接收前端传递的参数时
日期格式不匹配会报如下错误:JSON parse error: Cannot deserialize value of type
java.util.Date
from String "2023-10-1";就是说jsonq解析异常@PostMapping public String doSign(@RequestBody SignVO signVO){ System.out.println("userId:" + signVO.getUserId()); System.out.println("date:" + signVO.getSignDate()); return "123"; }
@Data public class SignVO { private Long userId; private Date signDate; }
解决方法就是给实体类的对应属性加Json解析格式化注解
JsonFormat
@Data public class SignVO { private Long userId; @JsonFormat(pattern = "yyyy-MM-dd") private Date signDate; }