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>
相关推荐
一隅论数智1 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
XiHongShi20161 天前
STM32F407 RTC定时器例程,建议保存
stm32·单片机·学习
爱吃苹果的日记本1 天前
离散数学第六课
学习·离散数学
AI职业加油站1 天前
AI智能体应用工程师证书:政策红利下的职业新风口
大数据·运维·人工智能·学习·职场发展
旖旎夜光1 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
奇思妙想聪明勤奋的小羊1 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
霍霍的袁1 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
彧azz1 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
Bingo_BIG1 天前
Java Spring框架:单表的查询、新增、修改、删除、导入、导出
java·spring·前后端