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>
相关推荐
sg_knight3 小时前
Spring 框架中的 SseEmitter 使用详解
java·spring boot·后端·spring·spring cloud·sse·sseemitter
郑州光合科技余经理6 小时前
同城系统海外版:一站式多语种O2O系统源码
java·开发语言·git·mysql·uni-app·go·phpstorm
一只乔哇噻6 小时前
java后端工程师+AI大模型开发进修ing(研一版‖day60)
java·开发语言·人工智能·学习·语言模型
Dolphin_Home6 小时前
笔记:SpringBoot静态类调用Bean的2种方案(小白友好版)
java·spring boot·笔记
MetaverseMan7 小时前
Java虚拟线程实战
java
浪潮IT馆7 小时前
Tomcat运行war包的问题分析与解决步骤
java·tomcat
悟能不能悟7 小时前
Caused by: java.sql.SQLException: ORA-28000: the account is locked怎么处理
java·开发语言
_院长大人_8 小时前
MyBatis Plus 分批查询优化实战:优雅地解决 IN 参数过多问题(实操)
java·mybatis
C雨后彩虹8 小时前
机器人活动区域
java·数据结构·算法·华为·面试