zoukankan      html  css  js  c++  java
  • Spring MVC 自定义转换器

    实现converter接口方法
     
    自定义转换器类代码如下:
    import org.springframework.core.convert.converter.Converter;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
     
    public class DateConvert implements Converter<String, Date> { 
        @Override 
        public Date convert(String stringDate) { 
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            Date d = null;
                    try {
                d = simpleDateFormat.parse(stringDate); 
            } catch (ParseException e) { 
                e.printStackTrace(); 
            } 
                return d; 
        }
    }
     
     
    Spring MVC中需要配置如下:
     
    <bean id="dateConvert" class="com.susq.springbegin.utils.DateConvert"/>
    <bean id="conversionService"
             class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
            <property name="dateConvert">
                    <set> <ref bean="stringToDateConverter"/> </set>
            </property> 
    </bean>
    <mvc:annotation-driven conversion-service="conversionService"/>
     

    也可以实现Formatter, 

    Formatter是一类特殊的Converter,专门处理字符串的转换

    类似于Converter, 修改实现和配置文件即可
     
    public class DateConvert implements Formatter<Date> {   
                 @Override 
                public Date parse(String s, Locale locale) throws ParseException { S
                impleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd"); 
                Date d = null; 
                            try { 
                    d = simpleDateFormat.parse(s); 
               } catch (ParseException e) {
                     e.printStackTrace(); 
                } 
                        return d; 
            } 
                @Override 
                public String print(Date date, Locale locale) { 
                        return null; 
            } 
    }
    配置文件如下:
    <bean id="dateConvert" class="com.susq.springbegin.utils.DateConvert"/> 
    <bean id="conversionService" 
            class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> 
            <property name="formatters"> 
                <set> <ref bean="dateConvert"/> </set> 
            </property> 
     </bean> 
    <mvc:annotation-driven conversion-service="conversionService"/>
     
     
    日期转换除了自定义还可以使用注解
    @DateTimeFormat(partten="yyyy-MM-dd")
  • 相关阅读:
    Django笔记
    在vue框架里添加bootstrap与axios
    Mysql8和Mysql5.7部署同一服务器
    docker迁入迁出mysql
    mysql导出csv
    Yearning启停脚本(开机自启)
    go 语言的基础知识
    阅读《深入理解Kafka核心设计与实践原理》第五章 日志存储
    阅读《深入理解Kafka核心设计与实践原理》第四章 主题与分区
    阅读《深入理解Kafka核心设计与实践原理》第三章 消费者
  • 原文地址:https://www.cnblogs.com/gaofz/p/7489714.html
Copyright © 2011-2022 走看看