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
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

SpringMVC数据格式化的更多相关文章

  1. 项目中整合第三方插件与SpringMVC数据格式化关于ip地址

    一.Bootstrap 响应式按钮 <div calss="col-sm-2"> <button class="btn btn-default btn- ...

  2. 【Spring学习笔记-MVC-9】SpringMVC数据格式化之日期转换@DateTimeFormat

    作者:ssslinppp       1. 摘要 本文主要讲解Spring mvc数据格式化的具体步骤: 并讲解前台日期格式如何转换为java对象: 在之前的文章<[Spring学习笔记-MVC ...

  3. SpringMVC框架下数据的增删改查,数据类型转换,数据格式化,数据校验,错误输入的消息回显

    在eclipse中javaEE环境下: 这儿并没有连接数据库,而是将数据存放在map集合中: 将各种架包导入lib下... web.xml文件配置为 <?xml version="1. ...

  4. SpringMVC 数据转换 & 数据格式化 & 数据校验

    数据绑定流程 1. Spring MVC 主框架将 ServletRequest 对象及目标方法的入参实例传递给 WebDataBinderFactory 实例,以创建 DataBinder 实例对象 ...

  5. SpringMVC(三)-- 视图和视图解析器、数据格式化标签、数据类型转换、SpringMVC处理JSON数据、文件上传

    1.视图和视图解析器 请求处理方法执行完成后,最终返回一个 ModelAndView 对象 对于那些返回 String,View 或 ModeMap 等类型的处理方法,SpringMVC 也会在内部将 ...

  6. SpringMVC——数据转换 & 数据格式化 & 数据校验

    一.数据绑定流程 1. Spring MVC 主框架将 ServletRequest 对象及目标方 法的入参实例传递给 WebDataBinderFactory 实例,以创 建 DataBinder ...

  7. SpringMVC的数据转换&&数据格式化&&数据校验

    1 SpringMVC的数据绑定流程 SpringMVC将ServletRequest对象及目标方法的入参实例传递给WebDataBinderFactory实例,以创建DataBinder实例对象. ...

  8. SpringMVC听课笔记(九:数据转换 & 数据格式化 & 数据校验)

    1.数据绑定流程 --1). Spring MVC主框架将ServletRequest对象及目标方法入参实例传递给WebDataBinderFactory实例,以创建DataBinder实例对象. - ...

  9. SpringMVC数据验证

    SpringMVC数据验证——第七章 注解式控制器的数据验证.类型转换及格式化——跟着开涛学SpringMVC 资源来自:http://jinnianshilongnian.iteye.com/blo ...

随机推荐

  1. jquery根据html()的内容来选择

    <ul><li>First</li><li>http://www.hfxskyyj.com/</li></ul> 如上,如何选中 ...

  2. python3快速安装升级pip3

    一.下载地址: 获取get-pip.py安装文件: 官网链接:https://bootstrap.pypa.io/get-pip.py 百度云链接:https://pan.baidu.com/s/14 ...

  3. Missing android.support.FILE_PROVIDER_PATHS meta-data 报错原因分析

    此类错误多半因为拼写错误导致.有StackOverflow上便有网友将"FILE_PROVIDER_PATHS"误写成"FILE_PROVIDE_PATHS"的 ...

  4. Fiddler讲解3

    想要 浏览更多Fiddler内容:请点击进入Fiddler官方文档 阅读目录: 一.Fiddler自定义请求: 二.Fiddler修改请求: 三.减少期望的延迟:100个继续标题: 四.重命名无效的P ...

  5. 在论坛中出现的比较难的sql问题:27(字符串拆分、字符串合并、非连续数字的间隔范围、随机返回字符串)

    原文:在论坛中出现的比较难的sql问题:27(字符串拆分.字符串合并.非连续数字的间隔范围.随机返回字符串) 在论坛中看到一个帖子,帖子中有一些sql方面的面试题,我觉得这些面试题很有代表性. 原帖的 ...

  6. Windows10无法远程连接

    1.在桌面计算机上,选择右键->属性.左侧任务列表中选择远程设置(如果桌面没有计算机图标,按键盘+R 输入 control system) 钩上允许 远程连接到此计算机 正常情况下,这样就可以在 ...

  7. sql server中:isnull(列名,0) 和isnull(列名,0)<>0 的区别

    1.isnull(参数1,参数2),判断参数1是否为NULL,如果是,返回参数2,否则返回参数1. 2.isnull(列名,0),isnull()函数是用来判断列名是否为null,如果为NUll,则返 ...

  8. winserver2012远程桌面进入只有CMD窗口,无桌面解决方法

    原因:.net framework4.5是Windows server图形化界面的基础,系统还原时只装了核心模式core,系统没有了图形界面当然只有cmd了   解决方法:使用dism命令需要将核心模 ...

  9. 拦截器中获取不到controller注解问题

    刚刚在测试接口的时候发现一个奇怪的问题:通过拦截器获取 controller 类注解,有些能获取到,有些又不能获取到,见鬼了. [环境]: 1. springboot :2.2.0.RELEASE [ ...

  10. Privacy Description

    This application respects and protects the privacy of all users who use the service. In order to pro ...