您好,登錄后才能下訂單哦!
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 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 來個完整的配置吧
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中)。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。