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.ISODateTimeFormat.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
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
SpringMVC数据格式化的更多相关文章
- 项目中整合第三方插件与SpringMVC数据格式化关于ip地址
一.Bootstrap 响应式按钮 <div calss="col-sm-2"> <button class="btn btn-default btn- ...
- 【Spring学习笔记-MVC-9】SpringMVC数据格式化之日期转换@DateTimeFormat
作者:ssslinppp 1. 摘要 本文主要讲解Spring mvc数据格式化的具体步骤: 并讲解前台日期格式如何转换为java对象: 在之前的文章<[Spring学习笔记-MVC ...
- SpringMVC框架下数据的增删改查,数据类型转换,数据格式化,数据校验,错误输入的消息回显
在eclipse中javaEE环境下: 这儿并没有连接数据库,而是将数据存放在map集合中: 将各种架包导入lib下... web.xml文件配置为 <?xml version="1. ...
- SpringMVC 数据转换 & 数据格式化 & 数据校验
数据绑定流程 1. Spring MVC 主框架将 ServletRequest 对象及目标方法的入参实例传递给 WebDataBinderFactory 实例,以创建 DataBinder 实例对象 ...
- SpringMVC(三)-- 视图和视图解析器、数据格式化标签、数据类型转换、SpringMVC处理JSON数据、文件上传
1.视图和视图解析器 请求处理方法执行完成后,最终返回一个 ModelAndView 对象 对于那些返回 String,View 或 ModeMap 等类型的处理方法,SpringMVC 也会在内部将 ...
- SpringMVC——数据转换 & 数据格式化 & 数据校验
一.数据绑定流程 1. Spring MVC 主框架将 ServletRequest 对象及目标方 法的入参实例传递给 WebDataBinderFactory 实例,以创 建 DataBinder ...
- SpringMVC的数据转换&&数据格式化&&数据校验
1 SpringMVC的数据绑定流程 SpringMVC将ServletRequest对象及目标方法的入参实例传递给WebDataBinderFactory实例,以创建DataBinder实例对象. ...
- SpringMVC听课笔记(九:数据转换 & 数据格式化 & 数据校验)
1.数据绑定流程 --1). Spring MVC主框架将ServletRequest对象及目标方法入参实例传递给WebDataBinderFactory实例,以创建DataBinder实例对象. - ...
- SpringMVC数据验证
SpringMVC数据验证——第七章 注解式控制器的数据验证.类型转换及格式化——跟着开涛学SpringMVC 资源来自:http://jinnianshilongnian.iteye.com/blo ...
随机推荐
- u盘传输文件时提示过大
(无需格式化U盘) 1.拷贝大文件时提示目标文件系统过大,无法复制 2.查U盘,发现剩余空间足够: 3.分析原因,是由于U盘的格式问题导致的,当期的磁盘格式是FAT32类型的,无拷贝过大的文件: 4. ...
- Hystrix【参数配置及缓存】
1.常用参数说明 hystrix参数的详细配置可参照 https://github.com/Netflix/Hystrix/wiki/Configuration 下面是一些常用的配置: 配置项 默认值 ...
- Mybatis笔记4
mybatis中多对多的步骤 示例:用户和角色,一个用户可以有多个角色,一个角色可以赋予多个用户 步骤: 建立两张表:用户表,角色表,让用户表和角色表具有多对多的关系,需要使用中间表,中间表中包含两张 ...
- Mybatis笔记1
Mybatis 持久层框架,数据访问层 mybatis是一个优秀的基于java的持久层框架,它内部封装了jdbc,使开发者只需要关注sql语句本身,而不需要花费精力去处理加载驱动,创建连接,创建sta ...
- C++ 中三种继承方式的理解
一.公有继承(public inheritance) 1.概念:当类的继承方式为公有继承时,基类的公有成员和保护成员的访问属性在派生类中不变,而基类的私有成员不可以直接访问. 实验一下: 我们用代 ...
- Burp Suite的安装与使用
Burp Suite是一个集成化的渗透测试工具,它集合了多种渗透测试组件,使我们自动化地或手工地能更好的完成对web应用的渗透测试和攻击.在渗透测试中,我们使用Burp Suite将使得测试工作变 ...
- FFMPEG - ffplay源代码分析
FFmpeg是一个开源,免费,跨平台的视频和音频流方案,它提供了一套完整的录制.转换以及流化音视频的解决方案.而ffplay是有ffmpeg官方提供的一个基于ffmpeg的简单播放器.学习ffplay ...
- git版本控制系统重新认识
git 版本控制系统 目标:完全搞懂git分布式版本控制系统 搭建git版本控制系统 cvs集中化版本控制系统--集中式管理的服务器 git分布式版本控制系统--会将原始代码仓库镜像下来 新项目使用g ...
- DevExtreme学习笔记(一) DataGrid中js分析
1.overviewjs采用 $(function() { $("#gridContainer").dxDataGrid({ dataSource: { store: { type ...
- 这些方面做好了才能叫运营-App运营日常
现在APP的开发推广是时代的潮流,同时也是不少企业的难题.现在我们就来谈谈APP运营的一些问题. 1. 基础运营正常维护产品最日常.最普通的工作,如APP应用包在各大应用市场提交上传等,如安卓渠道,包 ...