0061 Spring MVC的数据格式化--Formatter--FormatterRegistrar--@DateTimeFormat--@NumberFormat
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,除了上面的将其配置在FormattingConversionServiceFactoryBean
的formatters
属性中外,还可以像下面这样注册
写个类实现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的更多相关文章
- Spring MVC 前后台数据交互
本文是转载文章,感觉比较好,如有侵权,请联系本人,我将及时删除. 原文网址地址:<Spring MVC 前后台数据交互> 1.服务端数据到客户端 (1)返回页面,Controller中方法 ...
- 0060 Spring MVC的数据类型转换--ConversionService--局部PropertyEditor--全局WebBindingInitializer
浏览器向服务器提交的数据,多是字符串形式,而有些时候,浏览器需要Date.Integer等类型的数据,这时候就需要数据类型的转换器 使用Spring的ConversionService及转换器接口 下 ...
- Spring MVC -- 转换器和格式化
在Spring MVC -- 数据绑定和表单标签库中我们已经见证了数据绑定的威力,并学习了如何使用表单标签库中的标签.但是,Spring的数据绑定并非没有任何限制.有案例表明,Spring在如何正确绑 ...
- Spring MVC 数据转换和格式化
HttpMessageConverter和JSON消息转换器 HttpMessageConverter是定义从HTTP接受请求信息和应答给用户的 HttpMessageConverter是一个比较广的 ...
- spring mvc 4数据校验 validator
注解式控制器的数据验证.类型转换及格式化——跟着开涛学SpringMVC http://jinnianshilongnian.iteye.com/blog/1733708Spring4新特性——集成B ...
- 【Spring学习笔记-MVC-10】Spring MVC之数据校验
作者:ssslinppp 1.准备 这里我们采用Hibernate-validator来进行验证,Hibernate-validator实现了JSR-303验证框架支持注解风格的验证.首先 ...
- Spring MVC防止数据重复提交
现实开发中表单重复提交的例子很多,就包括手上这个门户的项目也有这种应用场景,用的次数多,但是总结,这还是第一次. 一.基本原理 使用token,给所有的url加一个拦截器,在拦截器里面用java的UU ...
- Spring MVC 的 Converter 和 Formatter
Converter 和 Formatter 都可用于将一种对象类型转换成另一种对象类型. Converter 是通用元件,可以将一种类型转换成另一种类型,可以在应用程序中的任意层中使用: Format ...
- Spring MVC防止数据重复提交(防止二次提交)
SpringMvc使用Token 使用token的逻辑是,给所有的url加一个拦截器,在拦截器里面用java的UUID生成一个随机的UUID并把这个UUID放到session里面,然后在浏览器做数据提 ...
随机推荐
- oracle汉字转拼音
CREATE OR REPLACE FUNCTION F_PINYIN(P_NAME IN VARCHAR2) RETURN VARCHAR2 AS V_COMPARE VARCHAR2(100); ...
- WCF项目中出现“目标程序集不包含服务类型”的解决办法
如果创建新项目时(以下简称A项目)选择的是WCF相关的项目模板,并且在A项目中只定义接口而不实现接口,那么任何引用了A项目的项目,在调试时都会弹出警告框“目标程序集不包含服务类型.可能需要调整此程序集 ...
- 关于actor-critic,这篇文章写的很好
这篇文章: https://blog.csdn.net/qq_30615903/article/details/80774384 可以好好温习,包括代码,基本看懂了.
- Informatica 常用组件Source Qualifier之六 外部联接
可以使用源限定符和应用程序源限定符转换在相同的数据库中执行两个源的外部联接.当 PowerCenter 执行外部联接时,它将返回其中一个源表的所有行和另一个源表中匹配联接条件的行. 如果您需要联接两个 ...
- CUDA,cudnn一些常见版本问题
- 最好的方法是官网说明: https://tensorflow.google.cn/install/source_windows Version Python version Compiler Bu ...
- ScaleIO 1.2 基础
The ScaleIO virtual SAN consists of 3 software components =================== Meta Data Manager (MDM ...
- Android -- Vibrator
Vibrator public c ...
- 【饿了么】—— Vue2.0高仿饿了么核心模块&移动端Web App项目爬坑(三)
前言:接着上一篇项目总结,这一篇是学习过程记录的最后一篇,这里会梳理:评论组件.商家组件.优化.打包.相关资料链接.项目github地址:https://github.com/66Web/ljq_el ...
- 转: SVN和Git的一些用法总结
转:http://www.codelast.com/?p=5719 转载请注明出处:http://www.codelast.com/ 以下都是比较基础的操作,高手们请绕道,不必浪费时间来看了. (A) ...
- spring mvc--默认都使用了哪些bean
在MVC中默认使用的bean都定义在了 org.springframework.web.servlet下的DispatcherServlet.properties 下载源文件后可查看到默认bean定义 ...