Spring中使⽤LocalDateTime、LocalDate等参数作为⼊参0x0 背景
项⽬中使⽤LocalDateTime系列作为dto中时间的类型,但是spring收到参数后总报错,为了全局配置时间类型转换,尝试了如下3中⽅法。
注:本⽂基于Springboot2.0测试,如果⽆法⽣效可能是spring版本较低导致的。PS:如果你的Controller中的LocalDate类型的参数啥注解(RequestParam、PathVariable等)都没加,也是会出错的,因为默认情况下,解析这种参数使⽤ModelAttributeMethodProcessor进⾏处理,⽽这个处理器要通过反射实例化⼀个对象出来,然后再对对象中的各个参数进⾏convert,但是LocalDate类没有构造函数,⽆法反射实例化因此会报错
0x1 当LocalDateTime作为RequestParam或者PathVariable时
这种情况要和时间作为Json字符串时区别对待,因为前端json转后端pojo底层使⽤的是Json序列化Jackson⼯具(HttpMessgeConverter);⽽时间字符串作为普通请求参数传⼊时,转换⽤的是Converter,两者有区别哦。
在这种情况下,有如下⼏种⽅案:
1. 使⽤Converter
import t.annotation.Bean;
import t.annotation.Configuration;
import verter.Converter;
import org.verter.HttpMessageConverter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Configuration
public class DateConfig {
@Bean
public Converter<String, LocalDate> localDateConverter() {
return new Converter<>() {
@Override
public LocalDate convert(String source) {
return LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
};
}
@Bean
public Converter<String, LocalDateTime> localDateTimeConverter() {
return new Converter<>() {
@Override
public LocalDateTime convert(String source) {
return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
};
}
}
以上两个bean会注⼊到spring mvc的参数解析器(好像叫做ParameterConversionService),当传⼊的字符串要转为LocalDateTime类时,spring会调⽤该Converter对这个⼊参进⾏转换。
2. 使⽤ControllerAdvice配合initBinder
@ControllerAdvice
public class GlobalExceptionHandler {
@InitBinder
protected void initBinder(WebDataBinder binder) {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
}
});
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
});
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(LocalTime.parse(text, DateTimeFormatter.ofPattern("HH:mm:ss")));
}
});
}
}
从名字就可以看出来,这是在controller做环切(这⾥⾯还可以全局异常捕获),在参数进⼊handler之前进⾏转换;转换为我们
相应的对象。
0x2 当LocalDateTime作为Json形式传⼊
这种情况下,如同上⽂描述,要利⽤Jackson的json序列化和反序列化来做:
@Configuration
public class JacksonConfig {
/** 默认⽇期时间格式 */
public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/** 默认⽇期格式 */
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
/** 默认时间格式 */
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
@Bean
public ObjectMapper objectMapper(){
ObjectMapper objectMapper = new ObjectMapper();
//      objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//      objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
javaTimeModule.addSerializer(LocalDate.class,new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
javaTimeModule.addSerializer(LocalTime.class,new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));    javaTimeModule.addDeserializer(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
javaTimeModule.addDeserializer(LocalTime.class,new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
return objectMapper;
}
}
0x3 来个完整的配置吧
package com.fig;
import com.JsonGenerator;
import com.JsonParser;
import com.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import t.annotation.Bean;
import t.annotation.Configuration;
import verter.Converter;
import java.io.IOException;
ParseException;
SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
@Configuration
public class DateConfig {
/** 默认⽇期时间格式 */
public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/** 默认⽇期格式 */
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
/** 默认时间格式 */
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
/**
* LocalDate转换器,⽤于转换RequestParam和PathVariable参数
*/
@Bean
public Converter<String, LocalDate> localDateConverter() {
return new Converter<>() {
@Override
public LocalDate convert(String source) {
return LocalDate.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT));
}
};
}
/**
* LocalDateTime转换器,⽤于转换RequestParam和PathVariable参数
*/
@Bean
public Converter<String, LocalDateTime> localDateTimeConverter() {
return new Converter<>() {
@Override
public LocalDateTime convert(String source) {
return LocalDateTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT));      }
};
}
/**
* LocalTime转换器,⽤于转换RequestParam和PathVariable参数
*/
@Bean
public Converter<String, LocalTime> localTimeConverter() {
return new Converter<>() {
@Override
public LocalTime convert(String source) {
return LocalTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT));
}
};
}
/**
* Date转换器,⽤于转换RequestParam和PathVariable参数
*/
@Bean
public Converter<String, Date> dateConverter() {
return new Converter<>() {
@Override
public Date convert(String source) {
SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
try {
return format.parse(source);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
};
}
/**
* Json序列化和反序列化转换器,⽤于转换Post请求体中的json以及将我们的对象序列化为返回响应的json    */
@Bean
public ObjectMapper objectMapper(){
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
//LocalDateTime系列序列化和反序列化模块,继承⾃jsr310,我们在这⾥修改了⽇期格式
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
javaTimeModule.addSerializer(LocalDate.class,new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
javaTimeModule.addSerializer(LocalTime.class,new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));    javaTimeModule.addDeserializer(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
javaTimeModule.addDeserializer(LocalTime.class,new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
//Date序列化和反序列化
javaTimeModule.addSerializer(Date.class, new JsonSerializer<>() {
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
String formattedDate = formatter.format(date);
jsonGenerator.writeString(formattedDate);
}
});
javaTimeModule.addDeserializer(Date.class, new JsonDeserializer<>() {
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
String date = Text();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
});
return objectMapper;
}
}
0x4 深⼊研究SpringMVC数据绑定过程
接下来进⼊debug模式,看看mvc是如何将我们request中的参数绑定到我们controller层⽅法⼊参的:
写⼀个简单controller,下个断点看看⽅法调⽤栈:
@GetMapping("/getDate")
public LocalDateTime getDate(@RequestParam LocalDate date,
@RequestParam LocalDateTime dateTime,
@RequestParam Date originalDate) {
System.out.println(date);
System.out.println(dateTime);
System.out.println(originalDate);
w();
}
断住以后,我们看下⽅法调⽤栈中⼀些关键⽅法:
//进⼊DispatcherServlet
doService:942, DispatcherServlet
//处理请求
doDispatch:1038, DispatcherServlet
//⽣成调⽤链(前处理、实际调⽤⽅法、后处理)
handle:87, AbstractHandlerMethodAdapter
/
/反射获取到实际调⽤⽅法,准备开始调⽤
invokeHandlerMethod:895, RequestMappingHandlerAdapter
invokeAndHandle:102, ServletInvocableHandlerMethod
//这⾥是关键,参数从这⾥开始获取到
invokeForRequest:142, InvocableHandlerMethod
doInvoke:215, InvocableHandlerMethod
//这个是Java reflect调⽤,因此⼀定是在这之前获取到的参数
invoke:566, Method
根据上述分析,发现invokeForRequest:142, InvocableHandlerMethod这⾥的代码是⽤来拿到实际参数的:
@Nullable
public Object invokeForRequest(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,
< providedArgs) throws Exception {
//这个⽅法是获取参数的,在这⾥下个断
Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
if (logger.isTraceEnabled()) {
}
//这⾥开始调⽤⽅法
return doInvoke(args);
}
进⼊这个⽅法看看是什么操作:
protected Object[] getMethodArgumentValues(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,
< providedArgs) throws Exception {
//获取⽅法参数数组,包含了⼊参信息,⽐如类型、泛型等等
MethodParameter[] parameters = getMethodParameters();
//这个⽤来存放⼀会从request parameter转换的参数
Object[] args = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
MethodParameter parameter = parameters[i];
parameter.initParameterNameDiscovery(this.parameterNameDiscoverer);
//这⾥看起来没啥卵⽤(providedArgs为空)
springboot是啥
args[i] = resolveProvidedArgument(parameter, providedArgs);
//这⾥开始获取到⽅法实际调⽤的参数,步进
if (this.argumentResolvers.supportsParameter(parameter)) {
//从名字就看出来:参数解析器解析参数
args[i] = solveArgument(parameter, mavContainer, request, this.dataBinderFactory);
continue;
}
}
return args;
}
进⼊resolveArgument看看:
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
//根据⽅法⼊参,获取对应的解析器
HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter);
//开始解析参数(把请求中的parameter转为⽅法的⼊参)
solveArgument(parameter, mavContainer, webRequest, binderFactory);
}
这⾥根据参数获取相应的参数解析器,看看内部如何获取的:
//遍历,调⽤supportParameter⽅法,跟进看看
for (HandlerMethodArgumentResolver methodArgumentResolver : this.argumentResolvers) {
if (methodArgumentResolver.supportsParameter(parameter)) {
result = methodArgumentResolver;
this.argumentResolverCache.put(parameter, result);
break;
}
}
这⾥,遍历参数解析器,查有没有适合的解析器!那么,有哪些参数解析器呢(我测试的时候有26个)我列出⼏个重要的看看,是不是很眼熟
{RequestParamMethodArgumentResolver@7686}
{PathVariableMethodArgumentResolver@8359}
{RequestResponseBodyMethodProcessor@8366}
{RequestPartMethodArgumentResolver@8367}
我们进⼊最常⽤的⼀个解析器看看他的supportsParameter⽅法,发现就是通过参数注解来获取相应的解析器的。
public boolean supportsParameter(MethodParameter parameter) {
//如果参数拥有注解@RequestParam,则⾛这个分⽀(知道为什么上⽂要对RequestParam和Json两种数据区别对待了把)
if (parameter.hasParameterAnnotation(RequestParam.class)) {
//这个似乎是对Optional类型的参数进⾏处理的
if (Map.class.stedIfOptional().getNestedParameterType())) {
RequestParam requestParam = ParameterAnnotation(RequestParam.class);
return (requestParam != null && StringUtils.hasText(requestParam.name()));
}
else {
return true;
}
}
//......
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。