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")
  • 相关阅读:
    40-cut 简明笔记
    50-ln 简明笔记
    35-less 简明笔记
    37-more 简明笔记
    9-cat 简明笔记
    64-who 简明笔记
    60-chmod 修改文件的权限
    useradd 添加用户
    14-find 查找文件
    层次越低的人,越容易放弃自己
  • 原文地址:https://www.cnblogs.com/gaofz/p/7489714.html
Copyright © 2011-2022 走看看