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>
相关推荐
传奇开心果编程37 分钟前
【Flutter入门练中学】第8课:动画与过渡
android·学习·flutter·ui·ios
后端LV1 小时前
一个注解不用写,给你的 Spring Boot 接口加上限流、日志、指标和钉钉告警
spring
程序员yu2 小时前
会编网络:别被入门教程骗了,Python实用能力不在语法本身
开发语言·python·学习·算法
Lintongzg2 小时前
千卡训练的隐形账单:通信不是瓶颈
笔记·学习·性能优化·llm
dadaobusi2 小时前
学习: SIOV
学习
卓怡学长2 小时前
w202springboot基于B_S架构的图书信息管理系统
java·spring boot·spring·intellij-idea
LuminousCPP2 小时前
从零开始学 C++(三):类和对象入门|从 struct 到 class,理解封装、对象与 this 指针
c++·笔记·学习·类和对象
景熙55232 小时前
JDBC 详解:从原理到实战(含完整可运行 Demo)
java·spring·tomcat·mybatis·jdbc
程序猿乐锅2 小时前
一文讲透缓存穿透、击穿和雪崩
java·redis·spring·缓存·mybatis
传奇开心果编程3 小时前
【Flutter入门练中学】第11课:状态管理进阶与声明式路由
android·学习·flutter·ui·ios