使用Formatter格式化数据 Day26 2018-12-1
2018-12-16 本文已影响0人
Ernest_Chou
“空杯心态”最直接的含义就是一个装满水的杯子很难接纳新东西,要将心里的“杯子”倒空,将自己所重视、在乎的很多东西以及曾经辉煌的过去从心态上彻底了结清空,只有将心倒空了,才会有外在的松手,才能拥有更大的成功。
1. 使用Formatter格式化数据
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类型对象。
1.1 实现Formatter<T>
接口
DateFormatter.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.springframework.format.Formatter;
//实现Formatter<T> 接口
public class DateFormatter implements Formatter<Date>{
// 日期类型模板:如yyyy-MM-dd
private String datePattern;
// 日期格式化对象
private SimpleDateFormat dateFormat;
// 构造器,通过依赖注入的日期类型创建日期格式化对象
public DateFormatter(String datePattern) {
this.datePattern = datePattern;
this.dateFormat = new SimpleDateFormat(datePattern);
}
// 显示Formatter<T>的T类型对象
@Override
public String print(Date date, Locale locale) {
return dateFormat.format(date);
}
// 解析文本字符串返回一个Formatter<T>的T类型对象。
@Override
public Date parse(String source, Locale locale) throws ParseException {
try {
return dateFormat.parse(source);
} catch (Exception e) {
throw new IllegalArgumentException();
}
}
}
1.2 springmvc
配置
springmvc-config.xml
<!-- 引入 xmlns:c="http://www.springframework.org/schema/c" -->
<!-- 装配自定义格式化转换器-->
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatters">
<list>
<bean class="com.formatter.DataFormatter" c:_0="yyyy-MM-dd"></bean>
</list>
</property>
</bean>
1.3 使用spring自带实现类
springmvc-config.xml
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatters">
<list>
<bean class="org.springframework.format.datetime.DateFormatter" p:pattern="yyyy-MM-dd HH:mm:ss"/>
</list>
</property>
</bean>
-
org.springframework.format.number
包中包含的其他实现类:-
NumberStyleFormatter
用于数字类型对象的格式化。 -
CurrencyStyleFormatter
用于货币类型对象的格式化。 -
PercentStyleFormatter
用于百分比数字类型对象的格式化。
-