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: 完整日期/时间的样式;
      • -: 忽略日期/时间的样式;
  • 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
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

最新文章

  1. 苹果 OS X 系统U盘重装-抹盘重装、系统盘制作
  2. Atitit.http代理的实现 代码java php c# python
  3. R语言 批量规划求解
  4. python计算器
  5. 线程的创建pthread_create.c
  6. (转)php-curl响应慢(开发微信授权登陆时碰到的问题)
  7. Libevent 定时器
  8. 【现代程序设计】加分作业1-对Stack的理解
  9. hdu 2544 最短路 Dijkstra
  10. BZOJ 2763
  11. asp.net ajax 检测用户名是否可用代码
  12. alwaysOn中关于维护计划的应用方案
  13. 初识Vue——模板语法
  14. Python Web-第二周-正则表达式(Using Python to Access Web Data)
  15. Delphi提取PDF文本
  16. python 27 获取时区转换后的时间
  17. Tomcat下JSP、Servlet和JavaBean环境的配置
  18. http协议与他的三次握手和四次挥手
  19. 简易搭建git仓库、关联远程和本地仓库方法。克隆仓库方法。同一台电脑上创建两个git ssh key方法。
  20. 关于FPGA复位的认识

热门文章

  1. as报错 Multiple root tags Unexpected tokens 这个都是编译器识别问题
  2. golang使用一个二叉树来实现一个插入排序
  3. teamviewer远程控制程序免费版百度云下载
  4. 题解-AtCoder ARC-083F Collecting Balls
  5. Windows方便得运行jar文件
  6. PHP即时实时输出内容
  7. linux的scp命令可以在linux服务器之间复制文件和目录
  8. 基于【 责任链模式】二 || 网关zuul过滤器封装
  9. nginx代理(正向代理和反向代理)
  10. element-ui 省市区联动组件 el-cascader