专业编程基础技术教程

网站首页 > 基础教程 正文

Spring对LocalDateTime入参接口返回值格式化

ccvgpt 2024-10-23 09:27:00 基础教程 7 ℃

背景

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

测试

我们有如下类,供测试

Spring对LocalDateTime入参接口返回值格式化

UserVO.java

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

1.接收参数时进行格式化

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请求传参,并将参数放在请求体中,此时,需要在接口的实体类前添加@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中,可配合上一个文件使用

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);
        };
    }
}

总结

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

最近发表
标签列表