作者:TinyThing 鏈接:https://www.jianshu.com/p/b52db905f020 ## 0x0 背景 > 項目中使用LocalDateTime系列作為dto中時間的類型,但是spring收到參數後總報錯,為了全局配置時間類型轉換,嘗試瞭如下3中方法。 > > **註:本文 ...
作者:TinyThing
鏈接:https://www.jianshu.com/p/b52db905f020
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,兩者有區別哦。
在這種情況下,有如下幾種方案:
推薦一個開源免費的 Spring Boot 實戰項目:
1. 使用Converter
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.converter.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) {
binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
}
});
binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
});
binder.registerCustomEditor(LocalTime.class, new PropertyEditorSupport() {
@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)));
objectMapper.registerModule(javaTimeModule).registerModule(new ParameterNamesModule());
return objectMapper;
}
}
0x3 來個完整的配置吧
Spring Boot 基礎就不介紹了,推薦看這個實戰項目:
package com.fly.hi.common.config;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.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 org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import java.io.IOException;
import java.text.ParseException;
import java.text.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 = jsonParser.getText();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
});
objectMapper.registerModule(javaTimeModule);
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);
return LocalDateTime.now();
}
斷住以後,我們看下方法調用棧中一些關鍵方法:
//進入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,
Object... providedArgs) throws Exception {
//這個方法是獲取參數的,在這裡下個斷
Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
if (logger.isTraceEnabled()) {
logger.trace("Arguments: " + Arrays.toString(args));
}
//這裡開始調用方法
return doInvoke(args);
}
進入這個方法看看是什麼操作:
protected Object[] getMethodArgumentValues(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,
Object... 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為空)
args[i] = resolveProvidedArgument(parameter, providedArgs);
//這裡開始獲取到方法實際調用的參數,步進
if (this.argumentResolvers.supportsParameter(parameter)) {
//從名字就看出來:參數解析器解析參數
args[i] = this.argumentResolvers.resolveArgument(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轉為方法的入參)
return resolver.resolveArgument(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.isAssignableFrom(parameter.nestedIfOptional().getNestedParameterType())) {
RequestParam requestParam = parameter.getParameterAnnotation(RequestParam.class);
return (requestParam != null && StringUtils.hasText(requestParam.name()));
}
else {
return true;
}
}
//......
}
也就是說,對於@RequestParam
和@RequestBody
以及@PathVariable
註解的參數,SpringMVC會使用不通的參數解析器進行數據綁定!
那麼,這三種解析器分別使用什麼Converter解析參數呢?我們分別進入三種解析器看一看:
首先看下RequestParamMethodArgumentResolver
發現內部使用WebDataBinder進行數據綁定,底層使用的是ConversionService (也就是我們的Converter註入的地方)
WebDataBinder binder = binderFactory.createBinder(webRequest, null, namedValueInfo.name);
//通過DataBinder進行數據綁定的
arg = binder.convertIfNecessary(arg, parameter.getParameterType(), parameter);
//跟進convertIfNecessary()
public <T> T convertIfNecessary(@Nullable Object value, @Nullable Class<T> requiredType,
@Nullable MethodParameter methodParam) throws TypeMismatchException {
return getTypeConverter().convertIfNecessary(value, requiredType, methodParam);
}
//繼續跟進,看到了把
ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
if (editor == null && conversionService != null && newValue != null && typeDescriptor != null) {
TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
try {
return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
}
catch (ConversionFailedException ex) {
// fallback to default conversion logic below
conversionAttemptEx = ex;
}
}
}
然後看下RequestResponseBodyMethodProcessor
發現使用的轉換器是HttpMessageConverter類型的:
//resolveArgument方法內部調用下麵進行參數解析
Object arg = readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType());
//step into readWithMessageConverters(),我們看到這裡的Converter是HttpMessageConverter
for (HttpMessageConverter<?> converter : this.messageConverters) {
Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass();
GenericHttpMessageConverter<?> genericConverter =
(converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter<?>) converter : null);
if (genericConverter != null ? genericConverter.canRead(targetType, contextClass, contentType) :
(targetClass != null && converter.canRead(targetClass, contentType))) {
if (message.hasBody()) {
HttpInputMessage msgToUse =
getAdvice().beforeBodyRead(message, parameter, targetType, converterType);
body = (genericConverter != null ? genericConverter.read(targetType, contextClass, msgToUse) :
((HttpMessageConverter<T>) converter).read(targetClass, msgToUse));
body = getAdvice().afterBodyRead(body, msgToUse, parameter, targetType, converterType);
}
else {
body = getAdvice().handleEmptyBody(null, message, parameter, targetType, converterType);
}
break;
}
}
最後看下PathVariableMethodArgumentResolver
發現 和RequestParam走的執行路徑一致(二者都是繼承自AbstractNamedValueMethodArgumentResolver解析器),因此代碼就不貼了。
0xFF總結
如果要轉換request傳來的參數到我們指定的類型,根據入參註解要進行區分:
- 如果是RequestBody,那麼通過配置ObjectMapper(這個玩意兒會註入到Jackson的HttpMessagConverter裡面,即
MappingJackson2HttpMessageConverter
中)來實現Json格式數據的序列化和反序列化;- 如果是RequestParam或者PathVariable類型的參數,通過配置Converter實現參數轉換(這些Converter會註入到ConversionService中)。
近期熱文推薦:
1.1,000+ 道 Java面試題及答案整理(2022最新版)
4.別再寫滿屏的爆爆爆炸類了,試試裝飾器模式,這才是優雅的方式!!
覺得不錯,別忘了隨手點贊+轉發哦!