后台LocalDateTime参数的接收问题(Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime‘)

在SpringMVC中通过@RequestParam接收jdk8的LocalDateTime时间类型的时候

前端通过传入

后台接收方式

会出现如下异常:

org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam java.time.LocalDateTime] for value '2018-11-11 12:12:12'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2018-11-11 12:12:12]

解决方式:

是通过@DateTimeFormat注解,去解析前端传入的时间格式字符串然后转化成LocaDateTime的时间类型

那么同时可以说一下

@JsonFormat:他和@DateTimeFormat正好对应关系,如果我们从DB中取得时间类型数据,想传回前端,并且规定格式,那么就可以使用@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")

 pattern:是你需要转换的时间日期的格式

 timezone:是时间设置为东八区,避免时间在转换中有误差

 提示:@JsonFormat注解可以在属性的上方,同样可以在属性对应的get方法上,两种方式没有区别

猜你喜欢

转载自www.cnblogs.com/h-java/p/10318435.html