項目中使用LocalDateTime系列做爲DTO中時間的數據類型,可是SpringMVC收到參數後總報錯,爲了配置全局時間類型轉換,嘗試了以下處理方式。注:本文基於Springboot2.x測試,若是沒法生效多是spring版本較低致使的。PS:若是你的Controller中的LocalDate類型的參數啥註解(RequestParam、PathVariable等)都沒加,也是會出錯的,由於默認狀況下,解析這種參數是使用
ModelAttributeMethodProcessor
進行處理,而這個處理器要經過反射實例化一個對象出來,而後再對對象中的各個參數進行convert,可是LocalDate類沒有構造函數,沒法反射實例化所以會報錯!!!
本文源碼解析部分引用自 Spring中使用LocalDateTime、LocalDate等參數做爲入參 ,原文寫的很精彩,建議仔細閱讀!!!前端
LocalTime
、localDate
和 LocalDateTime
這種狀況要和時間做爲Json字符串時區別對待,由於前端json轉後端pojo底層使用的是Json序列化Jackson工具(HttpMessgeConverter
);而時間字符串做爲普通請求參數傳入時,轉換用的是Converter
,二者在處理方式上是有區別。
實現 org.springframework.core.convert.converter.Converter,自定義參數轉換器,以下:java
@Configuration public class DateConverterConfig { @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對這個入參進行轉換。web
還能夠對前端傳遞的string進行正則匹配,如yyyy-MM-dd HH:mm:ss、yyyy-MM-dd、 HH:mm:ss等,進行匹配。以適應多種場景。spring
@Component public class DateConverter implements Converter<String, Date> { private static final String dateFormat = "yyyy-MM-dd HH:mm:ss"; @Override public Date convert(String value) { /** * 可對value進行正則匹配,支持日期、時間等多種類型轉換 * @param value * @return */ SimpleDateFormat formatter = new SimpleDateFormat(dateFormat); try { return formatter.parse(value); } catch (Exception e) { throw new RuntimeException(String.format("parser %s to Date fail", value)); } } }
使用spring自帶註解@DateTimeFormat(pattern = "yyyy-MM-dd"),以下:json
@DateTimeFormat(pattern = "yyyy-MM-dd") private Date startDate;
若是使用了自定義參數轉化器,Spring會優先使用該方式進行處理,即Spring註解不生效。後端
@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以前進行轉換;轉換爲咱們相應的對象。api
請求類型爲:post,content-type=application/json, 後臺用@RequestBody
接收,默認接收及返回值格式爲: yyyy-MM-dd HH:mm:ss
數組
在application.propertities文件中增長以下內容:springboot
spring: jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8
yyyy-MM-dd HH:mm:ss
的字符串,後臺用@RequestBody
接收,及返回值date轉爲yyyy-MM-dd HH:mm:ss
格式string;@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 MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = new ObjectMapper(); // 忽略json字符串中不識別的屬性 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 忽略沒法轉換的對象 objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); // PrettyPrinter 格式化輸出 objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); // NULL不參與序列化 objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 指定時區 objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); // 日期類型字符串處理 objectMapper.setDateFormat(new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT)); // java8日期日期處理 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); converter.setObjectMapper(objectMapper); return converter; } }
總結:mvc
yyyy-MM-dd HH:mm:ss
的字符串,後臺用@RequestBody
接收,及返回值Date轉爲yyyy-MM-dd HH:mm:ss
格式String;yyyy-MM-dd
等類型的字符串轉爲Date;以上兩種方式爲JSON入參的全局化處理,推薦使用方式二,尤爲適合大型項目在基礎包中全局設置。
場景: 假如全局日期時間處理格式爲:yyyy-MM-dd HH:mm:ss
,可是某個字段要求接收或返回日期yyyy-MM-dd
。
方式一
使用springboot自帶的註解@JsonFormat(pattern = "yyyy-MM-dd")
,以下所示:
@JsonFormat(pattern = "yyyy-MM-dd", timezone="GMT+8") private Date releaseDate;
點評: springboot默認提供,功能強大,知足常見場景使用,並可指定時區。
方式二
自定義日期序列化與反序列化,以下所示:
/** * 日期序列化 */ public class DateJsonSerializer extends JsonSerializer<Date> { @Override public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); jsonGenerator.writeString(dateFormat.format(date)); } } /** * 日期反序列化 */ public class DateJsonDeserializer extends JsonDeserializer<Date> { @Override public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); return dateFormat.parse(jsonParser.getText()); } catch (ParseException e) { throw new RuntimeException(e); } } } /** * 使用方式 */ @JsonSerialize(using = DateJsonSerializer.class) @JsonDeserialize(using = DateJsonDeserializer.class) private Date releaseDate;
@Configuration public class DateHandlerConfig { /** 默認日期時間格式 */ 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; } }
接下來進入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解析器),所以代碼就不貼了。
若是要轉換request傳來的參數到咱們指定的類型,根據入參註解要進行區分:
MappingJackson2HttpMessageConverter
中)來實現Json格式數據的序列化和反序列化;