SpringMVC学习笔记六:使用Formatter解析或格式化数据

转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6832903.html 

    Converter可以将一种类型转换成另一种类型,是任意Object之间的类型转换。

    Formatter则只能进行String与任意Object对象的转换,它提供 解析 与 格式化 两种功能。

    其中:解析是将String类型字符串转换为任意Object对象,格式化是将任意Object对象转换为字符串进行格式化显示。

     使用Formatter

    1: 实现Formatter<T>接口定义一个类,T为要解析得到或进行格式化的数据类型。

    在类中实现两个方法:String print(T t,Locale locale)和 T parse(String sourse,Locale locale),前者把T类型对象解析为字符串形式返回,后者由字符串解析得到T类型对象。

public class DateFormatter implements Formatter<Date>{
    private String datePattern;
    private SimpleDateFormat dateFormat;

    public DateFormatter(String datePattern) {
        this.dateFormat = dateFormat;
        dateFormat = new SimpleDateFormat(datePattern);
        dateFormat.setLenient(false);
    }
    public Date parse(String s, Locale locale) throws ParseException {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);
            dateFormat.setLenient(false);
            return dateFormat.parse(s);
        } catch (ParseException e) {
            throw new IllegalArgumentException("invalid date format. Please use this pattern"" + datePattern + """);
        }
    }

    public String print(Date date, Locale locale) {
        return dateFormat.format(date);
    }
}

    2:在SpringMVC配置文件中配置自定义格式转换器

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">//注册
    <property name="formatters">
        <set>//在FormattingConversionServiceFactoryBean中,formatters是一个set变量
            <bean class="路径.DateFormatter">//实现类的路径
                <constructor-arg name="datePattern" value="yyyy-MM-dd"/>//注入构造参数,指定格式
            </bean>
        </set>
    </property>
</bean>

<mvc:annotation-driven conversion-service="conversionService"/>//装配
原文地址:https://www.cnblogs.com/ygj0930/p/6832903.html