zoukankan      html  css  js  c++  java
  • springboot对LocalDateTime类型入参和接口返回值格式化

    背景

      使用过java8的朋友应该都知道LocalDateTime类型,它作为全新的日期和时间API ,对比Date类型有着很大的优势,极大的方便了我们对于时间和日期的操作。不过,如果在日常使用中,如果我们不对这个类型的字段进行处理的话,在打印或者直接返回到页面的时候往往看到的格式是这样的 2020-11-11T22:12:03.793 。显然这种格式对于用户来说阅读体验很差,那么,今天我们将通过这篇文章来介绍一下在使用LocalDateTime是如何在接受参数和返回信息时进行格式化。

    测试

    我们有如下类,供测试

    UserVO.java

    public class UserVO {
    
        private String userName;
        private String sex;
        private LocalDateTime birthday;
        //省略Getter and Setter方法
    
    }

    post请求使用formdata进行传参,这种情况下只需要在变量上添加@DateTimeFormat注解,案例如下:

    public class UserVO {
        private String userName;
        private String sex;
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime birthday;
        //省略Getter and Setter方法
    }
        @PostMapping("/testLocalDateTime")
        public UserVO testLocalDateTime(UserVO userVO) {
            System.out.println(userVO);
            return userVO;
        }
    

     调用之后可以看到控制台成功打印相关信息:

    接口返回:

     ② 使用post请求传参,并将参数放在请求体中以json格式传参,此时,需要在接口的实体类前添加@RequestBody注解,同时在LocalDateTime类型的变量上添加 @JsonFormat注解,案例如下:

        private String userName;
        private String sex;
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime birthday;
        //省略Getter and Setter方法
        @PostMapping("/testLocalDateTime2")
        public UserVO testLocalDateTime2(@RequestBody UserVO userVO) {
            System.out.println(userVO.toString());
            return userVO;
        }

    调用之后一样可以看到控制台成功打印相关信息:

     并且接口返回如下信息:

    这里我们可以注意到:这种情况下不需要添加额外配置,也会对返回值进行格式化

    补充

    如果项目中返回LocalDateTime类型字段过多的话一个一个去添加@JsonFormat显然是不合理的,那么我们可以在项目中添加如下配置,即可对所有LocalDateTime类型进行序列化和反序列化。

    LocalDateTimeConvertConfig.java

    此配置适用于于第一种情况,通过formDate进行传参

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.convert.converter.Converter;
    
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    
    
    @Slf4j
    @Configuration
    public class LocalDateTimeConvertConfig {
        @Bean
        public Converter<String, LocalDateTime> localDateTimeConvert() {
            return new Converter<String, LocalDateTime>() {
                @Override
                public LocalDateTime convert(String source) {
                    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    LocalDateTime dateTime = null;
                    try {
                        //2020-01-01 00:00:00
                        switch (source.length()) {
                            case 10:
                                log.debug("传过来的是日期格式:{}", source);
                                source = source + " 00:00:00";
                                break;
                            case 13:
                                log.debug("传过来的是日期 小时格式:{}", source);
                                source = source + ":00:00";
                                break;
                            case 16:
                                log.debug("传过来的是日期 小时:分钟格式:{}", source);
                                source = source + ":00";
                                break;
                        }
                        dateTime = LocalDateTime.parse(source, df);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                    return dateTime;
                }
            };
        }
    }

    LocalDateTimeSerializerConfig.java

    此配置适用于第二种情况,将请求参数放在requestbody中,可配合上一个文件使用,两种方法都可以对接口返回值中的LocalDateTime类型进行格式化

    import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
    import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    
    @Slf4j
    @Configuration
    public class LocalDateTimeSerializerConfig {
    
        @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
        private String pattern;
    
        // localDateTime 序列化器
        @Bean
        public LocalDateTimeSerializer localDateTimeSerializer() {
            return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
        }
    
        // localDateTime 反序列化器
        @Bean
        public LocalDateTimeDeserializer localDateTimeDeserializer() {
            return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(pattern));
        }
    
        @Bean
        public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    //        return new Jackson2ObjectMapperBuilderCustomizer() {
    //            @Override
    //            public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
    //                jacksonObjectMapperBuilder.featuresToDisable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    //                jacksonObjectMapperBuilder.serializerByType(LocalDateTime.class, localDateTimeSerializer());
    //                jacksonObjectMapperBuilder.deserializerByType(LocalDateTime.class, localDateTimeDeserializer());
    //            }
    //        };
            //这种方式同上
            return builder -> {
                builder.serializerByType(LocalDateTime.class, localDateTimeSerializer());
                builder.deserializerByType(LocalDateTime.class, localDateTimeDeserializer());
                builder.simpleDateFormat(pattern);
            };
        }
    }

     配置文件参考:https://blog.csdn.net/J080624/article/details/107065047/

    总结

    今天这篇文章主要讲解了springboot中如何对LocalDateTime进行格式化,同时还提供了配置类来更加方便的全局格式化LocalDateTime格式。

  • 相关阅读:
    2020牛客多校第三场 G
    Travel Guide
    jQuery属性选择器中加变量
    css 两大特性:继承性和层叠性
    css 伪元素选择器
    css 伪类选择器
    css属性选择器
    css的高级选择器,后代选择器,子代选择器,并集选择器,交集选择器
    css 引入方式以及css的选择器
    HTML
  • 原文地址:https://www.cnblogs.com/sueyyyy/p/13961442.html
Copyright © 2011-2022 走看看