springboot中配置前后端日期格式转化

一、说在前面

springboot的自动注入中内嵌了格式转化器,如果不做配置按照系统的默认时间格式请求和响应数据。

形如:Wed Mar 20 10:32:29 CST 2024

也就是说如果请求响应的数据和这个格式一样,就能成功,就不会报404

内嵌格式转化器:

支持自定义格式转化器的注册:

二、前端到后端日期格式转换

方法一:配置文件方法(在application.yml配置文件中)

复制代码
spring:
  mvc:
    date-format: yyyy-MM-dd

方法二:在实体类中日期属性前加DateTimeFormat注解

复制代码
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date birth;

方法三:自定义配置文件实现WebMvcConfigurer接口,重新格式转化器

复制代码
@Override
public void addFormatters(FormatterRegistry registry) {
    registry.addFormatter(new Formatter<Date>() {
        @Override
        public String print(Date date, Locale locale) {
            return null;
        }
        @Override
        public Date parse(String s, Locale locale) throws ParseException {
            return new SimpleDateFormat("yyyy-MM-dd").parse(s);
        }
    });
}

三、后端到前端日期格式转换

方法一:消息转化器和fastjson结合

fastjson是阿里的开源包,用于对json格式数据的解析处理。

在Spring MVC中,消息转换器(MessageConverter)是用于处理请求和响应中的数据转换的组件。它负责将HTTP请求中的数据转换为Java对象,并将Java对象转换为HTTP响应数据。常见的消息转换器包括处理JSON、XML、Form表单等格式的转换器。

pom.xml中引入fastjson依赖

复制代码
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.47</version>
</dependency>

在自定义配置类中配置消息转化器

复制代码
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    FastJsonHttpMessageConverter fc = new FastJsonHttpMessageConverter();
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
    fc.setFastJsonConfig(fastJsonConfig);
    converters.add(fc);
}

在实体类上加@jsonfield注解

复制代码
@JSONField(format = "yyyy-MM-dd")
private Date date;

四、一个注解请求响应双向日期格式转换

`@JSONFormat` 是Fastjson库中的注解,用于指定JSON序列化和反序列化时的格式化规则,如日期格式、数字格式等。这个注解可以用于类的字段上,以定制化JSON的格式化输出。

复制代码
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8"))
private Date birth;
//timezone用于指定是区,上面取值是东八区北京时间

注意在使用这个注解时请求的数据和响应的数据必须是json格式的。

相关推荐
candyTong15 小时前
阿里开源 AI Code Review 工具:ocr review 的执行链路解析
javascript·后端·架构
铁皮饭盒16 小时前
TypeBox 比 Zod.js 校验 快10倍, 还兼容AI 工具调用, 他做对了什么?
前端·javascript·后端
唐青枫16 小时前
Java 虚拟线程实战指南:从 Thread API 到 Spring Boot 高并发应用
java
倔强的石头_1 天前
WorkBuddy 上手实战:打造一个可用的本地 AI 工作台
后端
苍何1 天前
Coding 真有质的飞跃?实测下豆包seed 2.1 pro
后端
苍何1 天前
试了下腾讯 Marvis,回不去了...
后端
caibixyy1 天前
springboot+langchain4j 实战 Day14——工具嵌入多 Agent(Tool-Equipped Multi-Agent)
后端
caibixyy1 天前
springboot+langchain4j 实战 Day13 多 Agent 协作(Router + 子 Agent 分流)
后端
飘尘1 天前
前端转全栈(Java 后端)必须要知道的:开发中的锁机制与分布式并发控制
前端·后端·全栈