Spring MVC学习之——自定义日期转化器

日期转换器

在数据库中的日期数据是date类型,而如何我们想在页面自己添加数据,一般是使用年-月-日的形式,这种形式不仅date类型接收不到,而且传来的是String类型,此时,我们就可以自定义日期转换器来接收数据。

4.4.1.使用场景

  • 在index.jsp里面添加日期类型

    html 复制代码
        <form action="account/saveAccount" method="post">
          账户名称:<input type="text" name="name"><br/>
          账户金额:<input type="text" name="money"><br/>
          账户省份:<input type="text" name="address.provinceName"><br/>
          账户城市:<input type="text" name="address.cityName"><br/>
          开户日期:<input type="text" name="date"><br/>
          <input type="submit" value="保存">
        </form>
  • 在pojo里面添加日期类型

    java 复制代码
    public class Account implements Serializable {
        private Integer id;
        private String name;
        private Float money;
        private Address address;
        //添加日期类型
        private Date date;
        //省略get set toString方法
    }    
  • 测试


使用

  1. Converter接口说明:
  1. 定义一个类,实现Converter接口

    java 复制代码
    public class DateConverter implements Converter<String, Date> {
        @Override
        public Date convert(String source) {
            try {
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                return format.parse(source);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
  2. 在 springmvc.xml配置文件中配置类型转换器

    xml 复制代码
    	<!--开启springmvc注解支持-->
        <mvc:annotation-driven conversion-service="cs"></mvc:annotation-driven>
        <!-- 配置类型转换器工厂 -->
        <bean id="cs"
              class="org.springframework.context.support.ConversionServiceFactoryBean">
            <!-- 给工厂注入一个新的类型转换器 -->
            <property name="converters">
                <set>
                    <!-- 配置自定义类型转换器 -->
                    <bean class="com.by.converter.DateConverter"></bean>
                </set>
            </property>
        </bean>
相关推荐
一起学安全技术2 小时前
Java栈Agent开发 03|Spring AI(二):Tool Calling、MCP 与结构化输出
java·人工智能·spring·spring ai·结构化输出·mcp·tool calling
叼烟扛炮2 小时前
[LangGraph] 学习笔记(047):Pydantic 写的 State 也不校验,并行分支还互相看不见
笔记·学习
qq_274475152 小时前
第 16 篇:类型检测方案汇总:typeof、instanceof、Object.prototype.toString、手写 isType
javascript·学习·原型模式
CoderYanger3 小时前
Java EE 进阶:16. Spring原理(第一弹)
java·服务器·数据库·后端·spring·java-ee·github
Brain 博览记3 小时前
给吗啡类镇痛药装上“光开关”:照一下开、再照一下关——Cell 冷冻电镜解析阿片效价切换
开发语言·网络·论文阅读·学习·php
勤快的小雄哥哥3 小时前
青小关智能体,不小心把双数据源把主库 SqlSessionFactory 弄丢了
人工智能·spring·开源
Answer1st3 小时前
【FPGA学习】VSCode 写 Verilog 操作指南(XII)
vscode·学习·fpga开发
Nerd(BUG版)4 小时前
KMP学习day15--Compose副作用与动画
学习·kotlin·kmp
Monkey的自我迭代4 小时前
Kubernetes 声明式理念:只写“我要什么”
java·学习·kubernetes
不会画画的画师4 小时前
Spring IOC
java·后端·spring