Converter只完成了数据类型的转换,却不负责输入输出数据的格式化工作,日期时间、货币等虽都以字符串形式存在,却有不同的格式。

Spring格式化框架要解决的问题是:从格式化的数据中获取真正的数据,绑定数据,将处理完成的数据输出为格式化的数据。Formatter接口就是该框架最重要的接口

Converter主要是做Object与Object之间的类型转换,Formatter则是要完成任意Object与String之间的类型转换。前者适合于任何一层,而后者则主要用于web层

下面用Formatter接口完成0060中用converter完成的功能

先写个类实现Formatter接口

package net.sonng.mvcdemo.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale; import org.springframework.format.Formatter; public class DateFormatter implements Formatter<Date> {
private String datePattern;
private SimpleDateFormat dateFormat;
public DateFormatter(String datePattern){
this.datePattern=datePattern;
dateFormat=new SimpleDateFormat(datePattern);
}
@Override
public String print(Date date,Locale locale){
System.out.println("Date转String类型执行中。。。。");
return dateFormat.format(date);
}
@Override
public Date parse(String source,Locale locale) throws ParseException{
try{
System.out.println("字符串转Date类型执行中。。。。");
return dateFormat.parse(source);
}catch(Exception ex){
ex.printStackTrace();
throw new IllegalArgumentException();
}
}
}

配置xml

    <mvc:annotation-driven conversion-service="conversionService" />
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<!-- FormattingConversionServiceFactoryBean实现了ConversionService接口,具有类型转换和格式化的功能,既可以配置converters又可以配置formatters -->
<property name="formatters">
<list>
<bean class="net.sonng.mvcdemo.converter.DateFormatter" c:_0="dd-MM-yyyy" /> <!-- 注意日期格式日-月-年 -->
</list>
</property>
</bean>

访问index.html,输入数据,注意生日处按日月年的格式输入

使用FormatterRegistrar注册Formatter

要使用Formatter,除了上面的将其配置在FormattingConversionServiceFactoryBeanformatters属性中外,还可以像下面这样注册

写个类实现FormatterRegistrar

package net.sonng.mvcdemo.converter;

import org.springframework.format.FormatterRegistrar;
import org.springframework.format.FormatterRegistry; public class MyFormatterRegistrar implements FormatterRegistrar { //实现FormatterRegistrar接口
private DateFormatter dateFormatter; public void setDateFormatter(DateFormatter dateFormatter) { //setter
this.dateFormatter = dateFormatter;
} @Override
public void registerFormatters(FormatterRegistry registry) {
registry.addFormatter(dateFormatter); //注册给定的formatter
}
}

配置xml

    <mvc:annotation-driven conversion-service="conversionService" />
<bean id="dateFormatter" class="net.sonng.mvcdemo.converter.DateFormatter" c:_0="dd-MM-yyyy" /> <!-- 声明formatter的bean,提供给下面的MyFormatterRegistrar -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatterRegistrars"> <!-- 这里可以配置converters,formatters,还可以配置formatterRegistrars -->
<set>
<bean class="net.sonng.mvcdemo.converter.MyFormatterRegistrar" p:dateFormatter-ref="dateFormatter" />
</set>
</property>
</bean>

Spring提供的一些Formatter实现

实际上,Spring自身已经将DateFormatter写好了,位于org.springframework.format.datetime包下

另外在org.springframework.format.number包下面还提供了三个用于数字对象格式化的实现类

----NumberFormatter:用于数字类型

----CurrencyFormatter:用户货币类型

----PercentFormatter:用于百分数数字类型

用注解配置Formatter

先写个index.html,分别测试日期、整数、百分数、货币类型

<!DOCTYPE html>
<html>
<head>
<title>Spring MVC的数据类型转换</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="resources/jquery-3.1.0.js"></script>
<script type="text/javascript" src="resources/json2.js"></script> </head>
<body>
<form action="register" method="post">
日期类型:<input type="text" name="birthday" /> <br><br>
整数类型:<input type="text" name="total" /> <br><br>
百分数类型:<input type="text" name="discount" /><br><br>
货币类型:<input type="text" name="money" /><br><br>
<input type="submit" value="提交" />
</form>
</body>
</html>

实体类User,注解就加在该类的实例变量上

package net.sonng.mvcdemo.entity;

import java.util.Date;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style; public class User {
@DateTimeFormat(pattern="dd-MM-yyyy") //注解加在实例变量上
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;
//。。。。。。。
}

controller

package net.sonng.mvcdemo.controller;

import net.sonng.mvcdemo.entity.User;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
public class UserController { @RequestMapping("/register")
public String register(User user,Model model){
model.addAttribute("user", user);
return "result";
}
}

result.jsp

<%@page pageEncoding="utf-8"
contentType="text/html;charset=utf-8" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<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>

输入:



输出:



org.springframework.format.annotation包下有两个注解:@DateTimeForamt和@NumberFormat

@DateTimeFormat

可以注释java.util.Date, java.util.Calendar, java.lang.Long等时间类型的变量,拥有以下三个互斥属性

----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,使用自定义的时间格式化字符串,如yyyy-MM-dd hh:mm:ss

----style:类型为String,通过样式指定日期时间的格式,由两位字符组成,第一位表示日期,第二为表示时间

--------S:短日期时间样式

--------M:中日期时间样式

--------L:长日期时间样式

--------F:完整日期时间样式

---------:(短横线)忽略日期时间样式

@NumberFormat

可注释类似数字类型的实例变量,拥有两个互斥属性

----pattern:类型String,使用自定义的数字格式化串,如##,###表示50,000

----style:类型NumberFormat.Style,几个常用值:

--------Style.CURRENCY: 货币类型

--------Style.NUMBER: 正常数字类型

--------Style.PERCENT: 百分比类型

总结

数据格式化也包含了部分数据转换的内容

实现Formatter接口,重写print()与parse()方法,实现自定义的数据格式化

Spring MVC提供了几个格式化类:DateFormatter、NumberFormatter、CurrencyFormatter、PercentFormatter

利用注解@NumberFormat和@DateTimeFormat,注释在实体类的实例变量上,也可以实现日期、时间、数字的格式化

0061 Spring MVC的数据格式化--Formatter--FormatterRegistrar--@DateTimeFormat--@NumberFormat的更多相关文章

  1. Spring MVC 前后台数据交互

    本文是转载文章,感觉比较好,如有侵权,请联系本人,我将及时删除. 原文网址地址:<Spring MVC 前后台数据交互> 1.服务端数据到客户端 (1)返回页面,Controller中方法 ...

  2. 0060 Spring MVC的数据类型转换--ConversionService--局部PropertyEditor--全局WebBindingInitializer

    浏览器向服务器提交的数据,多是字符串形式,而有些时候,浏览器需要Date.Integer等类型的数据,这时候就需要数据类型的转换器 使用Spring的ConversionService及转换器接口 下 ...

  3. Spring MVC -- 转换器和格式化

    在Spring MVC -- 数据绑定和表单标签库中我们已经见证了数据绑定的威力,并学习了如何使用表单标签库中的标签.但是,Spring的数据绑定并非没有任何限制.有案例表明,Spring在如何正确绑 ...

  4. Spring MVC 数据转换和格式化

    HttpMessageConverter和JSON消息转换器 HttpMessageConverter是定义从HTTP接受请求信息和应答给用户的 HttpMessageConverter是一个比较广的 ...

  5. spring mvc 4数据校验 validator

    注解式控制器的数据验证.类型转换及格式化——跟着开涛学SpringMVC http://jinnianshilongnian.iteye.com/blog/1733708Spring4新特性——集成B ...

  6. 【Spring学习笔记-MVC-10】Spring MVC之数据校验

    作者:ssslinppp       1.准备 这里我们采用Hibernate-validator来进行验证,Hibernate-validator实现了JSR-303验证框架支持注解风格的验证.首先 ...

  7. Spring MVC防止数据重复提交

    现实开发中表单重复提交的例子很多,就包括手上这个门户的项目也有这种应用场景,用的次数多,但是总结,这还是第一次. 一.基本原理 使用token,给所有的url加一个拦截器,在拦截器里面用java的UU ...

  8. Spring MVC 的 Converter 和 Formatter

    Converter 和 Formatter 都可用于将一种对象类型转换成另一种对象类型. Converter 是通用元件,可以将一种类型转换成另一种类型,可以在应用程序中的任意层中使用: Format ...

  9. Spring MVC防止数据重复提交(防止二次提交)

    SpringMvc使用Token 使用token的逻辑是,给所有的url加一个拦截器,在拦截器里面用java的UUID生成一个随机的UUID并把这个UUID放到session里面,然后在浏览器做数据提 ...

随机推荐

  1. poj 1035 Spell checker ( 字符串处理 )

    Spell checker Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 16675   Accepted: 6087 De ...

  2. MFC中显示图像的放大、缩小、移动功能

    StretchBlt函数直接对图片进行放大,缩小,显示位置变换. 这个函数有两种形态一种全局函数是这样的:  BOOL StretchBlt(HDC hdcDest, int nXOriginDest ...

  3. jQuery调用WebService

    1.编写4种WebService方法     [WebService(Namespace = "http://tempuri.org/")]    [WebServiceBindi ...

  4. c# 注册表操作,创建,删除,修改,判断节点是否存在

    用.NET下托管语言C#操作注册表,主要内容包括:注册表项的创建,打开与删除.键值的创建(设置值.修改),读取和 删除.判断注册表项是否存在.判断键值是否存在. 准备工作: 1:要操作注册表,我们必须 ...

  5. 隐函数画图with R

    隐函数画图 with R 这个函数 sin(xsiny)-cos(ycosx)=0 图是这个样子 怎么用R画出来呢?下面是代码 x<-y<-seq(-10,20,0.1) f<-fu ...

  6. WebApi2 知识点总结

    1.建议使用异步接口async Task<> public async Task<IHttpActionResult> Get() 如果返回的是IEnumerable请使用: ...

  7. Spring事务属性具体解释

    Spring.是一个Java开源框架,是为了解决企业应用程序开发复杂性由Rod Johnson创建的.框架的主要优势之中的一个就是其分层架构,分层架构同意使用者选择使用哪一个组件,同一时候为 J2EE ...

  8. ServletConfig讲解

    1.1.配置Servlet初始化参数 在Servlet的配置文件web.xml中,可以使用一个或多个<init-param>标签为servlet配置一些初始化参数. 例如: <ser ...

  9. 类模板、Stack的类模板实现(自定义链栈方式,自定义数组方式)

    一.类模板 类模板:将类定义中的数据类型参数化 类模板实际上是函数模板的推广,可以用相同的类模板来组建任意类型的对象集合 (一).类模板的定义 template  <类型形参表> clas ...

  10. jQuery MiniUI自定义单元格

    监听处理"drawcell"事件 使用"drawcell"事件,可以自定义单元格内容.样式.行样式等. grid.on("drawcell" ...