Spring Boot深入分析講解日期時間處理
GET請求及POST表單日期時間字符串格式轉(zhuǎn)換
這種情況要和時間作為Json字符串時區(qū)別對待,因為前端json轉(zhuǎn)后端pojo底層使用的是Json序列化Jackson工具(HttpMessgeConverter);而時間字符串作為普通請求參數(shù)傳入時,轉(zhuǎn)換用的是Converter,兩者在處理方式上是有區(qū)別。
使用自定義參數(shù)轉(zhuǎn)換器(Converter)
實現(xiàn) org.springframework.core.convert.converter.Converter,自定義參數(shù)轉(zhuǎn)換器,如下:
@Configuration
public class DateConverterConfig {
@Bean
public Converter<String, LocalDate> localDateConverter() {
return new Converter<String, LocalDate>() {
@Override
public LocalDate convert(String source) {
return LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
};
}
@Bean
public Converter<String, LocalDateTime> localDateTimeConverter() {
return new Converter<String, LocalDateTime>() {
@Override
public LocalDateTime convert(String source) {
return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
};
}
}
點評:以上兩個bean會注入到spring mvc的參數(shù)解析器(好像叫做ParameterConversionService),當(dāng)傳入的字符串要轉(zhuǎn)為LocalDateTime類時,spring會調(diào)用該Converter對這個入?yún)⑦M(jìn)行轉(zhuǎn)換。
注意:關(guān)于自定義的參數(shù)轉(zhuǎn)換器 Converter,這有個坑,若將上面匿名內(nèi)部類的寫法精簡成lambda表達(dá)式的方式:
@Bean
@ConditionalOnBean(name = "requestMappingHandlerAdapter")
public Converter<String, LocalDate> localDateConverter() {
return source -> LocalDate.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT));
}
當(dāng)再次啟動項目時會出現(xiàn)異常:
Caused by: java.lang.IllegalArgumentException: Unable to determine source type <S> and target type <T> for your Converter [com.example.demo126.config.MappingConverterAdapter$$Lambda$522/817994751]; does the class parameterize those types?
是由于:
web項目啟動注冊requestMappingHandlerAdapter的時候會初始化WebBindingInitializer
adapter.setWebBindingInitializer(getConfigurableWebBindingInitializer());
而ConfigurableWebBindingInitializer需要FormattingConversionService, 而FormattingConversionService會將所有的Converter添加進(jìn)來,添加的時候需要獲取泛型信息:
@Override
public void addFormatters(FormatterRegistry registry) {
for (Converter<?, ?> converter : getBeansOfType(Converter.class)) {
registry.addConverter(converter);
}
for (GenericConverter converter : getBeansOfType(GenericConverter.class)) {
registry.addConverter(converter);
}
for (Formatter<?> formatter : getBeansOfType(Formatter.class)) {
registry.addFormatter(formatter);
}
}
添加Converter.class 一般是通過接口獲取兩個泛型的具體類型
public ResolvableType as(Class<?> type) {
if (this == NONE) {
return NONE;
}
Class<?> resolved = resolve();
if (resolved == null || resolved == type) {
return this;
}
for (ResolvableType interfaceType : getInterfaces()) {
ResolvableType interfaceAsType = interfaceType.as(type);
if (interfaceAsType != NONE) {
return interfaceAsType;
}
}
return getSuperType().as(type);
}
Lambda表達(dá)式的接口是Converter,并不能得到具體的類型,既然如此,那解決辦法:
- 最簡單的方法就是不適用Lambda表達(dá)式,還使用匿名內(nèi)部類,這樣就不會存在上述問題
- 就是等
requestMappingHandlerAdapterbean注冊完成之后再添加自己的converter就不會注冊到FormattingConversionService中
@Bean
@ConditionalOnBean(name = "requestMappingHandlerAdapter")
public Converter<String, LocalDateTime> localDateTimeConverter() {
return source -> LocalDateTime.parse(source, DateTimeUtils.DEFAULT_FORMATTER);
}
還可以對前端傳遞的string進(jìn)行正則匹配,如yyyy-MM-dd HH:mm:ss、yyyy-MM-dd、 HH:mm:ss等,進(jìn)行匹配。以適應(yīng)多種場景。
@Component
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String value) {
/**
* 可對value進(jìn)行正則匹配,支持日期、時間等多種類型轉(zhuǎn)換
* 這里在匹配Date日期格式時直接使用了 hutool 為我們已經(jīng)寫好的解析工具類,這里就不重復(fù)造輪子了
* cn.hutool.core.date.DateUtil
* @param value
* @return
*/
return DateUtil.parse(value.trim());
}
}
注:這里在匹配Date日期格式時直接使用了 hutool 為我們已經(jīng)寫好的解析工具類,這里就不重復(fù)造輪子了,下面的方法同樣使用了該工具類,想要在自己的項目中使用該工具類也很簡單,在項目pom文件中引入hutool的依賴就可以了,如下:
<!--hu tool 工具類--> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.1.3</version> </dependency>
使用Spring注解
使用spring自帶注解@DateTimeFormat(pattern = "yyyy-MM-dd"),如下:
@DateTimeFormat(pattern = "yyyy-MM-dd") private Date startDate;
如果使用了自定義參數(shù)轉(zhuǎn)化器,Spring會優(yōu)先使用該方式進(jìn)行處理,即Spring注解不生效。
使用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做環(huán)切(這里面還可以全局異常捕獲),在參數(shù)進(jìn)入handler之前進(jìn)行轉(zhuǎn)換;轉(zhuǎn)換為我們相應(yīng)的對象。
JSON入?yún)⒓胺祷刂等痔幚?/h2>
請求類型為:post,content-type=application/json, 后臺用@RequestBody接收,默認(rèn)接收及返回值格式為: yyyy-MM-dd HH:mm:ss
修改 application.yml 文件
在application.propertities文件中增加如下內(nèi)容:
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
支持(content-type=application/json)請求中格式為 yyyy-MM-dd HH:mm:ss的字符串,后臺用@RequestBody接收,及返回值date轉(zhuǎn)為yyyy-MM-dd HH:mm:ss格式string;
不支持(content-type=application/json)請求中yyyy-MM-dd等類型的字符串轉(zhuǎn)為date; 不支持java8日期api;
利用Jackson的JSON序列化和反序列化
@Configuration
public class JacksonConfig {
/** 默認(rèn)日期時間格式 */
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)時間格式 */
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);
// 忽略無法轉(zhuǎn)換的對象
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// PrettyPrinter 格式化輸出
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
// NULL不參與序列化
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 指定時區(qū)
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;
}
}總結(jié)
支持(content-type=application/json)請求中格式為yyyy-MM-dd HH:mm:ss的字符串,后臺用@RequestBody接收,及返回值Date轉(zhuǎn)為yyyy-MM-dd HH:mm:ss格式String;
支持java8日期api; 不支持(content-type=application/json)請求中yyyy-MM-dd等類型的字符串轉(zhuǎn)為Date; 以上兩種方式為JSON入?yún)⒌娜只幚?,推薦使用方式二,尤其適合大型項目在基礎(chǔ)包中全局設(shè)置。
到此這篇關(guān)于Spring Boot深入分析講解日期時間處理的文章就介紹到這了,更多相關(guān)Spring Boot日期時間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot無法請求html等靜態(tài)資源文件webapp或者resources/static的問題及解決方案
今天遇到一個問題無法訪問靜態(tài)資源文件,html,本文給大家分享SpringBoot無法請求html等靜態(tài)資源文件webapp或者resources/static的問題及解決方案,感興趣的朋友一起看看吧2024-05-05
編寫Java代碼對HDFS進(jìn)行增刪改查操作代碼實例
這篇文章主要介紹了Java代碼對HDFS進(jìn)行增刪改查操作,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
spring boot 如何優(yōu)雅關(guān)閉服務(wù)
這篇文章主要介紹了spring boot 如何優(yōu)雅關(guān)閉服務(wù),本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11
Windows中使用Java生成Excel文件并插入圖片的方法
這篇文章主要介紹了Windows中使用Java生成Excel文件并插入圖片的方法,其中向Excel中插入圖片文中通過使用Apache POI來實現(xiàn),需要的朋友可以參考下2016-02-02
啟動springboot項目時報錯:無法訪問org.springframework.web.bind.annotatio
這篇文章給大家分享了啟動springboot項目時報錯:?無法訪問org.springframework.web.bind.annotation.GetMapping …具有錯誤的版本 61.0,應(yīng)為52.0?的解決方案,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-10-10

