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 ...
随机推荐
- jpa简单demo调试druid
Druid连接池配置见https://www.cnblogs.com/blindjava/p/11504524.html pom <dependency> <groupId>m ...
- STM32之SPI时钟相位选择
SPI的时钟模式分为四种,由SPI_CR1寄存器的两位CPOL,CPHA组合选择. CPOL 如果为1,则时钟的空闲电平为高电平:CPOL 如果为0,则时钟的空闲电平为低电平.空闲电平影响不大. CP ...
- 剑指offer48:不用加减乘除做加法
1 题目描述 写一个函数,求两个整数之和,要求在函数体内不得使用+.-.*./四则运算符号. 2 思路和方法 位运算符:两个数异或(^)[1^0=1, 1^1=0, 0^0=0, 0^1=1, 5^5 ...
- hdu 6661 Acesrc and String Theory (后缀数组)
大意: 求重复$k$次的子串个数 枚举重复长度$i$, 把整个串分为$n/i$块, 如果每块可以$O(1)$计算, 那么最终复杂度就为$O(nlogn)$ 有个结论是: 以$j$开头的子串重复次数最大 ...
- 查看php和apache配置成功的方法
PHP配置文件是php.ini 检查php是否配置成功,在wamp/www根目录写一个phpinfo.php文件,内容为 <?php phpinfo(); ?> 然后可以打开网页输入l ...
- Linux 查询端口被占用命令
1.lsof -i:端口号 用于查看某一端口的占用情况,比如查看8000端口使用情况,lsof -i:8000 lsof -i:8080:查看8080端口占用 lsof abc.txt:显示开启文件a ...
- Spring Cloud Alibaba学习笔记(7) - Sentinel规则持久化及生产环境使用
Sentinel 控制台 需要具备下面几个特性: 规则管理及推送,集中管理和推送规则.sentinel-core 提供 API 和扩展接口来接收信息.开发者需要根据自己的环境,选取一个可靠的推送规则方 ...
- 数据结构与算法(周测3-Huffman树)
判断题 1.Given a Huffman tree for N (≥2) characters, all with different weights. The weight of any non- ...
- 在浏览器中输入www.taobao.com后执行的全部过程
>>>点击网址后,应用层的DNS协议会将网址解析为IP地址: DNS查找过程: 1. 浏览器会检查缓存中有没有这个域名对应的解析过的IP地址,如果缓存中有,这个解析过程 ...
- vue简单todolist
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...