" />

亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Spring Boot深入分析講解日期時間處理

 更新時間:2022年06月03日 10:38:01   作者:大夢誰先覺i  
項目中使用LocalDateTime系列作為DTO中時間的數(shù)據(jù)類型,但是SpringMVC收到參數(shù)后總報錯,為了配置全局時間類型轉(zhuǎn)換,嘗試了如下處理方式

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),當傳入的字符串要轉(zhuǎn)為LocalDateTime類時,spring會調(diào)用該Converter對這個入?yún)⑦M行轉(zhuǎn)換。

注意:關于自定義的參數(shù)轉(zhuǎn)換器 Converter,這有個坑,若將上面匿名內(nèi)部類的寫法精簡成lambda表達式的方式:

   @Bean
    @ConditionalOnBean(name = "requestMappingHandlerAdapter")
    public Converter<String, LocalDate> localDateConverter() {
        return source -> LocalDate.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT));
    }

當再次啟動項目時會出現(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添加進來,添加的時候需要獲取泛型信息:

@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表達式的接口是Converter,并不能得到具體的類型,既然如此,那解決辦法:

  • 最簡單的方法就是不適用Lambda表達式,還使用匿名內(nèi)部類,這樣就不會存在上述問題
  • 就是等requestMappingHandlerAdapterbean注冊完成之后再添加自己的converter就不會注冊到FormattingConversionService
@Bean
@ConditionalOnBean(name = "requestMappingHandlerAdapter")
public Converter<String, LocalDateTime> localDateTimeConverter() {
  return source -> LocalDateTime.parse(source, DateTimeUtils.DEFAULT_FORMATTER);
}

還可以對前端傳遞的string進行正則匹配,如yyyy-MM-dd HH:mm:ss、yyyy-MM-dd、 HH:mm:ss等,進行匹配。以適應多種場景。

@Component
public class DateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String value) {
        /**
         * 可對value進行正則匹配,支持日期、時間等多種類型轉(zhuǎn)換
         * 這里在匹配Date日期格式時直接使用了 hutool 為我們已經(jīng)寫好的解析工具類,這里就不重復造輪子了
         * cn.hutool.core.date.DateUtil
         * @param value
         * @return
         */
        return DateUtil.parse(value.trim());
    }
}

注:這里在匹配Date日期格式時直接使用了 hutool 為我們已經(jīng)寫好的解析工具類,這里就不重復造輪子了,下面的方法同樣使用了該工具類,想要在自己的項目中使用該工具類也很簡單,在項目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)先使用該方式進行處理,即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ù)進入handler之前進行轉(zhuǎn)換;轉(zhuǎn)換為我們相應的對象。

JSON入?yún)⒓胺祷刂等痔幚?/h2>

請求類型為:post,content-type=application/json, 后臺用@RequestBody接收,默認接收及返回值格式為: 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 {
    /** 默認日期時間格式 */
    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);
        // 忽略無法轉(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)⒌娜只幚?,推薦使用方式二,尤其適合大型項目在基礎包中全局設置。

到此這篇關于Spring Boot深入分析講解日期時間處理的文章就介紹到這了,更多相關Spring Boot日期時間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論