SpringMVC数据格式化
SpringMVC数据格式化
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用于百分比数字类型对象的格式化。
2. 使用FormatterRegistrar注册Formatter
2.1 实现FormatterRegistrar接口
MyFormatterRegistrar.java
import org.springframework.format.FormatterRegistrar; import org.springframework.format.FormatterRegistry; public class MyFormatterRegistrar implements FormatterRegistrar { private DateFormatter dateFormatter; public void setDateFormatter(DateFormatter dateFormatter) { this.dateFormatter = dateFormatter; } @Override public void registerFormatters(FormatterRegistry registry) { registry.addFormatter(dateFormatter); } }
2.2 springmvc配置
springmvc-config.xml
<!-- 引入 xmlns:c="http://www.springframework.org/schema/c" -->
<!-- 装配自定义格式化转换器-->
<mvc:annotation-driven conversion-service="conversionService"/>
<!-- DateFormatter bean -->
<bean id="dateFormatter" class="com.zhougl.web.formatter.DateFormatter"
c:_0="yyyy-MM-dd"/>
<!-- 格式化 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatterRegistrars">
<set>
<bean class="com.zhougl.web.formatter.MyFormatterRegistrar"
p:dateFormatter-ref="dateFormatter"/>
</set>
</property>
</bean>
3. 使用AnnotationFormatterFactory<A extends Annotation>格式化数据
3.1 注解
org.springframework.format.annotation包下定义的注解类:
注解
@JsonFormat主要是后台到前台的时间格式的转换
注解@DataFormat主要是前后到后台的时间格式的转换
-
DateTimeFormat,互斥属性:-
iso。类型为
DateTimeFormat.ISO-
DateTimeFormat.ISO.DATE: 格式yyyy-MM-dd。 -
DateTimeFormat.ISO.DATE_TIME: 格式yyyy-MM-dd HH:mm:ss .SSSZ。 -
DateTimeFormat.ISO.TIME: 格式HH:mm:ss .SSSZ。 -
DateTimeFormat.ISO.NONE: 表示不使用ISO格式的时间。
-
- pattern。类型为String,使用自定义的时间格式化字符串。
-
style。类型为String,通过样式指定日期时间的格式,由两位字符组成,第1位表示日期的样式,第2位表示时间的格式:
- S: 短日期/时间的样式;
- M: 中日期/时间的样式;
- L: 长日期/时间的样式;
- F: 完整日期/时间的样式;
- -: 忽略日期/时间的样式;
-
iso。类型为
-
NumberFormat- pattern。类型为String,使用自定义的数字格式化字符串,"##,###.##"。
-
style。类型为
NumberFormat.Style,常用值:-
Style.NUMBER正常数字类型 -
Style.PERCENT百分数类型 -
Style.CURRENCY货币类型
-
3.2 注解实体类
// 域对象,实现序列化接口 public class User implements Serializable{ // 日期类型 @DateTimeFormat(pattern="yyyy-MM-dd") private Date birthday; // 正常数字类型 @NumberFormat(style=Style.NUMBER, pattern="#,###") private int total; // 百分数类型 @NumberFormat(style=Style.PERCENT) private double discount; // 货币类型 @NumberFormat(style=Style.CURRENCY) private double money; ... }
3.3 Controller层
@Controller public class FormatterController{ private static final Log logger = LogFactory.getLog(FormatterController.class); @RequestMapping(value="/{formName}") public String loginForm(@PathVariable String formName){ // 动态跳转页面 return formName; } @RequestMapping(value="/test",method=RequestMethod.POST) public String test( @ModelAttribute User user, Model model) { logger.info(user); model.addAttribute("user", user); return "success"; } }
3.4 jsp
testForm.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试AnnotationFormatterFactory 接口</title>
</head>
<body>
<h3>测试表单数据格式化</h3>
<form action="test" method="post">
<table>
<tr>
<td><label>日期类型: </label></td>
<td><input type="text" id="birthday" name="birthday" ></td>
</tr>
<tr>
<td><label>整数类型: </label></td>
<td><input type="text" id="total" name="total" ></td>
</tr>
<tr>
<td><label>百分数类型: </label></td>
<td><input type="text" id="discount" name="discount" ></td>
</tr>
<tr>
<td><label>货币类型: </label></td>
<td><input type="text" id="money" name="money" ></td>
</tr>
<tr>
<td><input id="submit" type="submit" value="提交"></td>
</tr>
</table>
</form>
</body>
</html>
success.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试AnnotationFormatterFactory</title>
</head>
<body>
<h3>测试表单数据格式化</h3>
<form:form modelAttribute="user" method="post" action="" >
<table>
<tr>
<td>日期类型:</td>
<td><form:input path="birthday"/></td>
</tr>
<tr>
<td>整数类型:</td>
<td><form:input path="total"/></td>
</tr>
<tr>
<td>百分数类型:</td>
<td><form:input path="discount"/></td>
</tr>
<tr>
<td>货币类型:</td>
<td><form:input path="money"/></td>
</tr>
</table>
</form:form>
</body>
</html>
3.5 springmvc配置
<!-- 默认装配 -->
<mvc:annotation-driven/>
作者:Ernest_Chou
链接:https://www.jianshu.com/p/a837926e9946
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
浙公网安备 33010602011771号