SpringMVC系列之(六)自定义类型转换器

自定义类型转换器

SpringMVC在进行请求参数绑定时,自动进行了类型转换,前端传来的参数都是字符串,而控制器中的方法在接收时,可能会用到其他数据类型(如:Date、Integer、Double等),以日期类型为例,前端传的日期格式多样,SpringMVC自动转换类型的格式(2011/11/11)支持不了这么多类型,故有的日期格式(如:2011-11-11)需要自行转换:自定义类型转换器实现
在这里插入图片描述
在这里插入图片描述

25-Mar-2022 10:30:27.278 璀﹀憡 [http-nio-8080-exec-87] org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.logException Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'user' on field 'date': rejected value [2011-11-11]; codes [typeMismatch.user.date,typeMismatch.date,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.date,date]; arguments []; default message [date]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2011-11-11'; nested exception is java.lang.IllegalArgumentException]]

步骤如下:

  1. 创建自定义类型转换器
package cn.itcast.utils;

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

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

/**
 * @author 商务小本本
 * Converter<S,T>的两个泛型
 *	S:原类型
 *	T:要转换成的类型
 */
public class StringToDateConverter implements Converter<String, Date> {
    /**
     *
     * @param s 传入的原类型数据,在这就是字符串
     * @return
     */
    @Override
    public Date convert(String s) {
        if (s == null){
            throw new RuntimeException("请您传入数据");
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return dateFormat.parse(s);
        } catch (ParseException e) {
            throw new RuntimeException("数据类型转换出现错误");
        }
    }
}
  1. 配置自定义类型转换器并注入创建的自定义类型转换器
<bean class="org.springframework.context.support.ConversionServiceFactoryBean" id="conversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="cn.itcast.utils.StringToDateConverter"></bean>
        </set>
    </property>
</bean>
  1. 开始SpringMVC对自定义类型转换器的支持
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"></mvc:annotation-driven>
posted @ 2024-02-28 08:43  刘二水  阅读(149)  评论(0)    收藏  举报