您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“Spring中如何使用LocalDateTime、LocalDate等參數(shù)作為入?yún)ⅰ?,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“Spring中如何使用LocalDateTime、LocalDate等參數(shù)作為入?yún)ⅰ卑?
0x0 背景
項(xiàng)目中使用LocalDateTime系列作為dto中時(shí)間的類型,但是spring收到參數(shù)后總報(bào)錯(cuò),為了全局配置時(shí)間類型轉(zhuǎn)換,嘗試了如下3中方法。
注:本文基于Springboot2.0測(cè)試,如果無(wú)法生效可能是spring版本較低導(dǎo)致的。PS:如果你的Controller中的LocalDate類型的參數(shù)啥注解(RequestParam、PathVariable等)都沒(méi)加,也是會(huì)出錯(cuò)的,因?yàn)槟J(rèn)情況下,解析這種參數(shù)使用ModelAttributeMethodProcessor進(jìn)行處理,而這個(gè)處理器要通過(guò)反射實(shí)例化一個(gè)對(duì)象出來(lái),然后再對(duì)對(duì)象中的各個(gè)參數(shù)進(jìn)行convert,但是LocalDate類沒(méi)有構(gòu)造函數(shù),無(wú)法反射實(shí)例化因此會(huì)報(bào)錯(cuò)?。?!
0x1 當(dāng)LocalDateTime作為RequestParam或者PathVariable時(shí)
這種情況要和時(shí)間作為Json字符串時(shí)區(qū)別對(duì)待,因?yàn)榍岸薺son轉(zhuǎn)后端pojo底層使用的是Json序列化Jackson工具(HttpMessgeConverter);而時(shí)間字符串作為普通請(qǐng)求參數(shù)傳入時(shí),轉(zhuǎn)換用的是Converter,兩者有區(qū)別哦。在這種情況下,有如下幾種方案:
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;@Configurationpublic 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")); } }; }}
以上兩個(gè)bean會(huì)注入到spring mvc的參數(shù)解析器(好像叫做ParameterConversionService),當(dāng)傳入的字符串要轉(zhuǎn)為L(zhǎng)ocalDateTime類時(shí),spring會(huì)調(diào)用該Converter對(duì)這個(gè)入?yún)⑦M(jìn)行轉(zhuǎn)換。
2. 使用ControllerAdvice配合initBinder
@ControllerAdvicepublic 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"))); } }); }}
從名字就可以看出來(lái),這是在controller做環(huán)切(這里面還可以全局異常捕獲),在參數(shù)進(jìn)入handler之前進(jìn)行轉(zhuǎn)換;轉(zhuǎn)換為我們相應(yīng)的對(duì)象。
0x2 當(dāng)LocalDateTime作為Json形式傳入
這種情況下,如同上文描述,要利用Jackson的json序列化和反序列化來(lái)做:
@Configurationpublic class JacksonConfig { /** 默認(rèn)日期時(shí)間格式 */ public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** 默認(rèn)日期格式 */ public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd"; /** 默認(rèn)時(shí)間格式 */ 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 來(lái)個(gè)完整的配置吧
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;@Configurationpublic class DateConfig { /** 默認(rèn)日期時(shí)間格式 */ public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** 默認(rèn)日期格式 */ public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd"; /** 默認(rèn)時(shí)間格式 */ public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss"; /** * LocalDate轉(zhuǎn)換器,用于轉(zhuǎn)換RequestParam和PathVariable參數(shù) */ @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轉(zhuǎn)換器,用于轉(zhuǎn)換RequestParam和PathVariable參數(shù) */ @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轉(zhuǎn)換器,用于轉(zhuǎn)換RequestParam和PathVariable參數(shù) */ @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轉(zhuǎn)換器,用于轉(zhuǎn)換RequestParam和PathVariable參數(shù) */ @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序列化和反序列化轉(zhuǎn)換器,用于轉(zhuǎn)換Post請(qǐng)求體中的json以及將我們的對(duì)象序列化為返回響應(yīng)的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,我們?cè)谶@里修改了日期格式 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數(shù)據(jù)綁定過(guò)程
接下來(lái)進(jìn)入debug模式,看看mvc是如何將我們r(jià)equest中的參數(shù)綁定到我們controller層方法入?yún)⒌模?/p>
寫(xiě)一個(gè)簡(jiǎn)單controller,下個(gè)斷點(diǎn)看看方法調(diào)用棧:
@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(); }
斷住以后,我們看下方法調(diào)用棧中一些關(guān)鍵方法:
//進(jìn)入DispatcherServletdoService:942, DispatcherServlet//處理請(qǐng)求doDispatch:1038, DispatcherServlet//生成調(diào)用鏈(前處理、實(shí)際調(diào)用方法、后處理)handle:87, AbstractHandlerMethodAdapter//反射獲取到實(shí)際調(diào)用方法,準(zhǔn)備開(kāi)始調(diào)用invokeHandlerMethod:895, RequestMappingHandlerAdapterinvokeAndHandle:102, ServletInvocableHandlerMethod//這里是關(guān)鍵,參數(shù)從這里開(kāi)始獲取到invokeForRequest:142, InvocableHandlerMethoddoInvoke:215, InvocableHandlerMethod//這個(gè)是Java reflect調(diào)用,因此一定是在這之前獲取到的參數(shù)invoke:566, Method
根據(jù)上述分析,發(fā)現(xiàn)invokeForRequest:142, InvocableHandlerMethod這里的代碼是用來(lái)拿到實(shí)際參數(shù)的:
@Nullable public Object invokeForRequest(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception { //這個(gè)方法是獲取參數(shù)的,在這里下個(gè)斷 Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs); if (logger.isTraceEnabled()) { logger.trace("Arguments: " + Arrays.toString(args)); } //這里開(kāi)始調(diào)用方法 return doInvoke(args); }
進(jìn)入這個(gè)方法看看是什么操作:
protected Object[] getMethodArgumentValues(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception { //獲取方法參數(shù)數(shù)組,包含了入?yún)⑿畔?,比如類型、泛型等? MethodParameter[] parameters = getMethodParameters(); //這個(gè)用來(lái)存放一會(huì)從request parameter轉(zhuǎn)換的參數(shù) Object[] args = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { MethodParameter parameter = parameters[i]; parameter.initParameterNameDiscovery(this.parameterNameDiscoverer); //這里看起來(lái)沒(méi)啥卵用(providedArgs為空) args[i] = resolveProvidedArgument(parameter, providedArgs); //這里開(kāi)始獲取到方法實(shí)際調(diào)用的參數(shù),步進(jìn) if (this.argumentResolvers.supportsParameter(parameter)) { //從名字就看出來(lái):參數(shù)解析器解析參數(shù) args[i] = this.argumentResolvers.resolveArgument(parameter, mavContainer, request, this.dataBinderFactory); continue; } } return args; }
進(jìn)入resolveArgument看看:
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception { //根據(jù)方法入?yún)?,獲取對(duì)應(yīng)的解析器 HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter); //開(kāi)始解析參數(shù)(把請(qǐng)求中的parameter轉(zhuǎn)為方法的入?yún)ⅲ? return resolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory); }
這里根據(jù)參數(shù)獲取相應(yīng)的參數(shù)解析器,看看內(nèi)部如何獲取的:
//遍歷,調(diào)用supportParameter方法,跟進(jìn)看看 for (HandlerMethodArgumentResolver methodArgumentResolver : this.argumentResolvers) { if (methodArgumentResolver.supportsParameter(parameter)) { result = methodArgumentResolver; this.argumentResolverCache.put(parameter, result); break; } }
這里,遍歷參數(shù)解析器,查找有沒(méi)有適合的解析器!那么,有哪些參數(shù)解析器呢(我測(cè)試的時(shí)候有26個(gè))???我列出幾個(gè)重要的看看,是不是很眼熟?。?!
{RequestParamMethodArgumentResolver@7686} {PathVariableMethodArgumentResolver@8359} {RequestResponseBodyMethodProcessor@8366} {RequestPartMethodArgumentResolver@8367}
我們進(jìn)入最常用的一個(gè)解析器看看他的supportsParameter方法,發(fā)現(xiàn)就是通過(guò)參數(shù)注解來(lái)獲取相應(yīng)的解析器的。
public boolean supportsParameter(MethodParameter parameter) { //如果參數(shù)擁有注解@RequestParam,則走這個(gè)分支(知道為什么上文要對(duì)RequestParam和Json兩種數(shù)據(jù)區(qū)別對(duì)待了把) if (parameter.hasParameterAnnotation(RequestParam.class)) { //這個(gè)似乎是對(duì)Optional類型的參數(shù)進(jìn)行處理的 if (Map.class.isAssignableFrom(parameter.nestedIfOptional().getNestedParameterType())) { RequestParam requestParam = parameter.getParameterAnnotation(RequestParam.class); return (requestParam != null && StringUtils.hasText(requestParam.name())); } else { return true; } } //...... }
也就是說(shuō),對(duì)于@RequestParam和@RequestBody以及@PathVariable注解的參數(shù),SpringMVC會(huì)使用不通的參數(shù)解析器進(jìn)行數(shù)據(jù)綁定!
那么,這三種解析器分別使用什么Converter解析參數(shù)呢?我們分別進(jìn)入三種解析器看一看:
首先看下RequestParamMethodArgumentResolver發(fā)現(xiàn)內(nèi)部使用WebDataBinder進(jìn)行數(shù)據(jù)綁定,底層使用的是ConversionService (也就是我們的Converter注入的地方)
WebDataBinder binder = binderFactory.createBinder(webRequest, null, namedValueInfo.name);//通過(guò)DataBinder進(jìn)行數(shù)據(jù)綁定的arg = binder.convertIfNecessary(arg, parameter.getParameterType(), parameter); //跟進(jìn)convertIfNecessary() public <T> T convertIfNecessary(@Nullable Object value, @Nullable Class<T> requiredType, @Nullable MethodParameter methodParam) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, methodParam); } //繼續(xù)跟進(jìn),看到了把 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發(fā)現(xiàn)使用的轉(zhuǎn)換器是HttpMessageConverter類型的:
//resolveArgument方法內(nèi)部調(diào)用下面進(jìn)行參數(shù)解析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發(fā)現(xiàn) 和RequestParam走的執(zhí)行路徑一致(二者都是繼承自AbstractNamedValueMethodArgumentResolver解析器),因此代碼就不貼了。
0xFF總結(jié)
如果要轉(zhuǎn)換request傳來(lái)的參數(shù)到我們指定的類型,根據(jù)入?yún)⒆⒔庖M(jìn)行區(qū)分:
如果是RequestBody,那么通過(guò)配置ObjectMapper(這個(gè)玩意兒會(huì)注入到Jackson的HttpMessagConverter里面,即MappingJackson2HttpMessageConverter中)來(lái)實(shí)現(xiàn)Json格式數(shù)據(jù)的序列化和反序列化;如果是RequestParam或者PathVariable類型的參數(shù),通過(guò)配置Converter實(shí)現(xiàn)參數(shù)轉(zhuǎn)換(這些Converter會(huì)注入到ConversionService中)。
到此,相信大家對(duì)“Spring中如何使用LocalDateTime、LocalDate等參數(shù)作為入?yún)ⅰ庇辛烁畹牧私?,不妨?lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。