当前位置: 首页 > ai >正文

Spring MVC中自定义日期类型格式转换器

在Spring MVC中,自定义日期类型格式转换器可以通过实现Converter接口或使用@DateTimeFormat注解。以下是两种方法的详细说明:


方法一:全局自定义转换器(推荐)

1. 创建日期转换器类

实现 org.springframework.core.convert.converter.Converter 接口:

import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;public class StringToDateConverter implements Converter<String, Date> {private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";@Overridepublic Date convert(String source) {SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);try {return format.parse(source);} catch (ParseException e) {throw new IllegalArgumentException("日期格式错误,请使用 " + DATE_FORMAT, e);}}
}
2. 注册转换器到Spring容器
方法1:通过配置类实现 WebMvcConfigurer
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void addFormatters(FormatterRegistry registry) {registry.addConverter(new StringToDateConverter());}
}
方法2:通过配置applicationContex.xml实现:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><!-- 1. 声明自定义转换器 --><bean id="stringToDateConverter" class="com.example.converter.StringToDateConverter"/><!-- 2. 配置 ConversionService --><bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"><property name="converters"><set><ref bean="stringToDateConverter"/><!-- 可添加其他转换器,如日期转字符串 --></set></property></bean><!-- 3. 启用 MVC 注解驱动并关联 ConversionService --><mvc:annotation-driven conversion-service="conversionService"/><!-- 其他配置(如组件扫描、视图解析器等) --><context:component-scan base-package="com.example.controller"/>
</beans>

方法二:局部使用 @DateTimeFormat

直接在实体类字段上标注日期格式:

import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;public class MyEntity {@DateTimeFormat(pattern = "yyyy/MM/dd")private Date createTime;// Getter & Setter
}

使用 Java 8 的 DateTimeFormatter(更安全)

如果使用Java 8+,建议用 DateTimeFormatter 替代 SimpleDateFormat

import org.springframework.core.convert.converter.Converter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");@Overridepublic LocalDateTime convert(String source) {return LocalDateTime.parse(source, FORMATTER);}
}

注册方式与全局转换器相同。


注意事项:

  1. 时区处理:如果涉及跨时区,需在格式化时指定时区:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());
    
  2. 异常处理:转换失败时会抛出 IllegalArgumentException,可在Controller中捕获并处理。

  3. 多格式支持:若需支持多种格式,可在转换器中按顺序尝试不同格式。


通过以上步骤,即可实现全局或局部的日期格式自定义转换。

http://www.xdnf.cn/news/2790.html

相关文章:

  • 单片机-89C51部分:8、定时器
  • 6.3 数据分析与决策支持:数据洞察生成与决策辅助系统
  • 机器学习实操 第一部分 机器学习基础 第6章 决策树
  • jmeter-Beashell获取http请求体json
  • 在K8S迁移节点kubelet数据存储目录
  • 道德经解读分析
  • Android 进阶开发:深入掌握 ProgressBar 的使用与高级技巧
  • 文献阅读(三)基于干旱强度和恢复时间的生态系统恢复力评估|《Agricultural and Forest Meteorology》
  • 在 Ubuntu 上离线安装 ClickHouse
  • 【数据结构】图论存储结构深度解析:邻接多重表如何实现无向图O(1)删边?邻接矩阵/链表/十字链对比
  • 无锡哲讯科技:SAP财务系统——赋能企业智慧财务管理
  • 开发iOS App时,我常用的一款性能监控小工具分享
  • 数据库中DDL、DML、DCL的区别是什么?
  • Webug4.0通关笔记04- 第6关宽字节注入
  • 洛谷P12238 [蓝桥杯 2023 国 Java A] 单词分类
  • 从车道检测项目入门open cv
  • 【图片识别成表格】批量图片识别成excel表格,批量识别图片区域文字保存到excel表格,基于WPF和腾讯OCR的识别方案
  • MyBatis 使用 POJO 参数动态查询教程
  • leetcode继续c++10/100
  • UDP数据报和TCP流套接字编程
  • BUUCTF——Online Tool
  • 日本IT行业|salesforce开发语言占据的地位
  • Java后端开发day39--方法引用
  • 如何系统学习音视频
  • gitmodule怎么维护
  • 千问3(Qwen3)模型开源以及初体验
  • 设计模式(工厂模式)
  • Android Studio Profiler
  • 矩阵区域和 --- 前缀和
  • 【计算机视觉】目标检测:深度解析YOLOv5:下一代实时目标检测框架实战指南