Spring MVC自定义类型转换器!!!

使用场景

在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方法
}  

测试

原因:我们前台传递的是字符串类型的参数,但是后台使用的是Date类型接收的。我们期望springmvc可以帮我们做数据类型的自动转换,显然没有做,所以我们需要自己自定义类型转换器。

解决方案:

定义一个类,实现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;
    }
}

在 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>
相关推荐
qq_185198697 小时前
(Spring Bean + delegateExpression)实现http服务 的完整可运行项目
spring
小Ti客栈8 小时前
Spring Boot 集成 Springdoc-OpenAPI 与 Knife4j实现接口文档与可视化调试
java·spring boot·后端
Ai拆代码的曹操8 小时前
Spring 事务 REQUIRES_NEW 嵌套调用:连接池翻倍的秘密
java·后端·spring
动恰客流统计9 小时前
ReID边缘计算视觉统计:餐饮店客流增长的数字化破局路径
java·大数据·运维·人工智能
Ivanqhz10 小时前
Rust &‘static str浅析
java·前端·javascript·rust
weixin_4196583112 小时前
Docker 搭建 Jenkins 服务
java·docker·jenkins
captain37613 小时前
多线程线程安全问题
java·java-ee
CoderYanger13 小时前
A.每日一题:1979. 找出数组的最大公约数
java·程序人生·算法·leetcode·面试·职场和发展·学习方法
灵极海13 小时前
LangChain4j RAG 实战完整指南:从入门到踩坑
java·langchain
yaoxin52112313 小时前
476. Java 反射 - 调用方法
java·开发语言