zoukankan      html  css  js  c++  java
  • springmvc自定义类型转换器

    springmvc自定义类型转换器

    表单提交的任何数据类型全部都是字符串类型,但是后台定义Integer类型,数据也可以封装上,说明Spring框架内部会默认进行数据类型转换。如果想自定义数据类型转换,可以实现Converter的接口

    1、自定义类型转换器

    package cn.itcast.utils; 
    import java.text.DateFormat; import java.text.SimpleDateFormat; 
    import java.util.Date; 
    import org.springframework.core.convert.converter.Converter;
    
    /**
    * 把字符串转换成日期的转换器 
    * @author rt 
    */ 
    public class StringToDateConverter implements Converter<String, Date>{ 
        /**
        *进行类型转换的方法 
        */
        public Date convert(String source) { 
            // 判断 
            if(source == null) { 
                throw new RuntimeException("参数不能为空");
            }
    		try {
       		   DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 
                // 解析字符串 
                Date date = df.parse(source); 
                return date;
            } catch (Exception e) { 
                throw new RuntimeException("类型转换错误");
            }
        } 
    }
    

    2、注册自定义类型转换器

    在springmvc.xml配置文件中编写配置

    <!-- 配置类型转换器工厂 -->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> 
        <!-- 给工厂注入一个新的类型转换器 -->
        <property name="converters"> 
            <!-- 配置自定义类型转换器 -->
            <set><bean class="cn.itcast.utils.StringToDateConverter"/></set> 
        </property> 
    </bean>
    <!-- 引用自定义类型转换器 -->
    <mvc:annotation-driven conversion-service="converterService"></mvc:annotation-driven>
    
    记得快乐
  • 相关阅读:
    hadoop 2.x 简单实现wordCount
    httpClient连接超时设置
    Java io使用简介
    log4j使用教程
    F#中的自定义隐式转换
    Computation expressions and wrapper types
    Introducing 'bind'
    Understanding continuations
    Computation expressions: Introduction
    MySQL优化总结,百万级数据库优化方案
  • 原文地址:https://www.cnblogs.com/Y-wee/p/13838889.html
Copyright © 2011-2022 走看看