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>
相关推荐
胡萝卜3.010 小时前
掌握string类:从基础到实战
c++·学习·string·string的使用
果粒chenl10 小时前
React学习(四) --- Redux
javascript·学习·react.js
im_AMBER11 小时前
CSS 01【基础语法学习】
前端·css·笔记·学习
艾菜籽11 小时前
Spring MVC入门补充2
java·spring·mvc
向阳花开_miemie11 小时前
Android音频学习(二十二)——音频接口
学习·音视频
胡萝卜3.011 小时前
深入理解string底层:手写高效字符串类
开发语言·c++·学习·学习笔记·string类·string模拟实现
fanstering11 小时前
腾讯混元P3-SAM: Native 3D Part Segmentation
笔记·学习·3d·点云
im_AMBER12 小时前
数据结构 05 栈和队列
数据结构·笔记·学习
风兮w12 小时前
MVC、MVP和MVVM的区别
mvc
报错小能手12 小时前
linux学习笔记(31)网络编程——TCP time_wait机制
linux·笔记·学习