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>
相关推荐
ps酷教程3 小时前
Jackson 解决没有无参构造函数的反序列化问题
java
NiceCloud喜云3 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
_日拱一卒4 小时前
LeetCode:994腐烂的橘子
java·数据结构·算法·leetcode·深度优先
隔窗听雨眠4 小时前
Nginx网关响应慢排查手记
java·服务器·nginx
智慧物业老杨5 小时前
智慧物业合同周期管理系统:从风险预警到智能交接的全流程数智化落地方案
java·人工智能·python
源码宝5 小时前
MES系统源码:Java8 + SpringBoot2.7 + MySQL8 + Redis,后端源码清爽易扩展
java·后端·源码·springboot·mes系统·源码二开·mes源码
JAVA社区6 小时前
Java高级全套教程(十)—— SpringCloudAlibaba超详细实战详解
java·开发语言·spring cloud·面试·职场和发展
金銀銅鐵6 小时前
[Java] 如何理解 class 文件中方法的 descriptor?
java·后端
云烟成雨TD6 小时前
Spring AI Alibaba 1.x 系列【63】AI Agent 长期记忆
java·人工智能·spring
憧憬成为java架构高手的小白6 小时前
苍穹外卖--day09
java·spring boot·百度