SpringMVC自定义数据类型转换器

要解决的问题

springMVC自带了很多自动的数据类型转换器,比如String转Integer,String转Date等,但在String转Date中,2021-01-01无法自动转为Date,所以就需要我们自定义一个数据类型转换类;

步骤

1、写一个String转Date的转换类,该类实现Converter接口,并复写其中的convert方法

package cn.gpxxg.utils.converter;

import org.springframework.core.convert.converter.Converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 类型转换,把String转为Date
 */
public class StringToDate implements Converter<String, Date> {
    @Override
    public Date convert(String s) {
        if (s == null)
            throw new RuntimeException("请您传入数据");

        DateFormat date = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        try {
            parse = date.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return parse;
    }
}

2、在springmvc配置文件中配置自定义类型转换器,注入ConversionServiceFactoryBean并加入我们自定义的转换类,并在mvc:annotation-driven中开启自定义类型转换的支持

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

    <!--创建容器时要扫码的包-->
    <context:component-scan base-package="cn.gpxxg"></context:component-scan>

    <!--加载视图解析器进容器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--配置跳转地址的前缀-->
        <property name="prefix" value="/WEB-INF/pages/"></property>

        <!--配置跳转地址的后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--配置自定义类型转换器-->
    <bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="cn.gpxxg.utils.converter.StringToDate"></bean>
            </set>
        </property>
    </bean>

    <!--springMVC框架开启注解支持-->
    <mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>
</beans>

3、写个页面自测吧

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值