类型转换器


字符串转date类型注意

2021/12/12格式的可以自动转换;不需要自定义类型转换器
2021-12-12格式的不会自动转换;需要自定义类型转换器

自定义类型转换器

SpringMVC提供Converter<S,T>接口;
包:org.springframework.core.convert.converter.Converter
说明:该接口有两个泛型,S:表示接受的类型,T:表示目标的类型
使用:

  1. 定义类实现Converter接口,实现convert方法
    import org.springframework.core.convert.converter.Converter;
    import java.util.Date;
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    
    public class StringToDateConverter implements Converter<String, Date> {
        @Override
        public Date convert(String s) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = null;
            try {
                parse = dateFormat.parse(s);
            } catch (ParseException e) {
                e.printStackTrace();
                throw new RuntimeException("日期格式错误!");
            }
            return parse;
        }
    }
  2. 在 spring 配置文件中配置类型转换器
    spring 配置类型转换器的机制是,将自定义的转换器注册到类型转换服务中去
    <!-- 配置类型转换器工厂 --> 
    <bean id="converterService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <!-- 给工厂注入一个新的类型转换器 --> 
      <property name="converters"> 
        <array>
          <!-- 配置自定义类型转换器 --> 
          <bean class="com.itheima.web.converter.StringToDateConverter"></bean>
        </array>
      </property>
    </bean>
  3. spring 配置文件的 mvc:annotation-driven 标签中引用配置的类型转换服务
    <!-- 引用自定义类型转换器 --> 
    <mvc:annotation-driven conversion-service="converterService"></mvc:annotation-driven>

文章作者: zrh
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 zrh !
  目录