spring - springMVC - 自定义类型转换

https://www.cnblogs.com/clamp7724/p/11703406.html

在这个基础上修改的

spring中设置了自动的类型转换,可以把前台数据自动进行类型转换传给后台,不过有些特殊情况可能需要自己定义类型转换

比如前台传回String 2019/10/21  后台是可以自动转化为 Date 的

但是如果是 2019-10-21 就会报错

这时候就需要自定义类型转换并加到spring中。

reference: https://www.bilibili.com/video/av50213945/?p=14

第一步:定义一个类,实现Converter接口,该接口有两个泛型。

第二步:

在springmvc.xml (springmvc的配置文件,在resources下面)里的beans里添加新的bean

<!-- 配置类型转换器工厂 添加新的类型转换-->
    <bean id="converterService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <!-- 给工厂注入一个新的类型转换器 -->
        <property name="converters">
            <array> <!-- 配置自定义类型转换器 这里class是自己写的转换类的完整名字(路径+名字)-->
                <bean class="hello_word.method.MyStringToDate"></bean>
            </array>
        </property>
    </bean>

第三步:在annotation-driven标签中引用配置的类型转换服务

<mvc:annotation-driven conversion-service="converterService"></mvc:annotation-driven>

修改后整个springmvc的代码:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<!-- 配置spring创建容器时要扫描的包 -->
<context:component-scan base-package="hello_word"></context:component-scan>

<!-- 配置视图解析器,  决定controller对应的显示页面去哪找-->
<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置spring开启注解mvc的支持-->
<mvc:annotation-driven conversion-service="converterService"></mvc:annotation-driven>

    <!-- 配置类型转换器工厂 添加新的类型转换-->
    <bean id="converterService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <!-- 给工厂注入一个新的类型转换器 -->
        <property name="converters">
            <array> <!-- 配置自定义类型转换器,这里class是自己写的转换类的完整名字(路径+名字) -->
                <bean class="hello_word.method.MyStringToDate"></bean>
            </array>
        </property>
    </bean>
</beans>

修改java代码和jsp用于测试

user 添加 Date birthday属性,添加get,set,修改toString

前台表单添加

用户生日(yyyy-mm-dd):<input type="text" name = 'user.birthday'><br/>

测试结果:

 

猜你喜欢

转载自www.cnblogs.com/clamp7724/p/11712751.html