项目中使用LocalDateTime系列作为dto中时间的类型,但是spring收到参数后总报错,为了全局配置时间类型转换,尝试了如下3中方法。0x1 当LocalDateTime作为RequestParam或者PathVariable时
注:本文基于Springboot2.0测试,如果无法生效可能是spring版本较低导致的。PS:如果你的Controller中的LocalDate类型的参数啥注解(RequestParam、PathVariable等)都没加,也是会出错的,因为默认情况下,解析这种参数使用ModelAttributeMethodProcessor进行处理,而这个处理器要通过反射实例化一个对象出来,然后再对对象中的各个参数进行convert,但是LocalDate类没有构造函数,无法反射实例化因此会报错!!!
这种情况要和时间作为Json字符串时区别对待,因为前端json转后端pojo底层使用的是Json序列化Jackson工具(HttpMessgeConverter);而时间字符串作为普通请求参数传入时,转换用的是Converter,两者有区别哦。推荐一个开源免费的 Spring Boot 实战项目:
在这种情况下,有如下几种方案:
https://github.com/javastacks/spring-boot-best-practice1. 使用Converter
以上两个bean会注入到spring mvc的参数解析器(好像叫做ParameterConversionService),当传入的字符串要转为LocalDateTime类时,spring会调用该Converter对这个入参进行转换。2. 使用ControllerAdvice配合initBinder
从名字就可以看出来,这是在controller做环切(这里面还可以全局异常捕获),在参数进入handler之前进行转换;转换为我们相应的对象。0x2 当LocalDateTime作为Json形式传入
这种情况下,如同上文描述,要利用Jackson的json序列化和反序列化来做:
https://github.com/javastacks/spring-boot-best-practice
接下来进入debug模式,看看mvc是如何将我们request中的参数绑定到我们controller层方法入参的:写一个简单controller,下个断点看看方法调用栈:
近期热文推荐:
- 如果是RequestBody,那么通过配置ObjectMapper(这个玩意儿会注入到Jackson的HttpMessagConverter里面,即MappingJackson2HttpMessageConverter中)来实现Json格式数据的序列化和反序列化;
- 如果是RequestParam或者PathVariable类型的参数,通过配置Converter实现参数转换(这些Converter会注入到ConversionService中)。
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) | Powered by Discuz! X3.4 |