在Java的开发中,经常需要进行数据类型的转换,最常见的就是字符型转成Date类型存入数据库。以下介绍三种数据类型转换的方法。

一,使用ConversionService转换数据

二,使用自定义编辑器转换数据

三,注册全局自定义编辑器转换数据

1,  使用ConversionService转换数据类型,需要自定义一个转换器,在该转换器类中实现所需要的数据类型的转换,该类需要实现Converter<S,T>接口。

Converter<S,T>接口是spring中最简单的转换器接口,接口中只有一个方法:

T convert (S source),该接口的作用很明显,就是将S类型的对象转换为T类型的对象。

那么具体如何使用ConversionService来实现数据类型的转换呢?

以日期类型为例,日期类型开发中见得最多,我们往往需要输入的是yyyy-MM-dd这种格式的字符串,但是定义的Date类型的接收参数无法直接转换,所以不做处理往往会报数据转换异常。

下面的例子通过ConversionService来实现字符串到日期类型数据的转换。

首先定义一个实体类:

package org.amuxia.pojo;import java.util.Date;public class User {private String username;private String password;private Date birthday;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public User(String username, String password, Date birthday) {super();this.username = username;this.password = password;this.birthday = birthday;}public User() {super();// TODO Auto-generated constructor stub}}

接着写一个控制器类,这里只做数据转换的测试,直接注册成功即可。

package org.amuxia.controller;import org.amuxia.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;@Controller
public class UserController {@RequestMapping("/toRegist")public String toRegist(){return "regist";}@RequestMapping(value="/regist",method=RequestMethod.POST)public String regist(@ModelAttribute User user,Model model){model.addAttribute("userinfo",user);return "success";}
}

定义两个jsp页面,一个做注册使用,一个做注册成功后的跳转页面并在该页面显示出转换后的数据格式:

Regist.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户注册</title>
</head>
<body><form action="regist.action" method="post"><table><tr><td>昵称</td><td><input type="text" name="username" ></td></tr><tr><td>密码</td><td><input type="password" name="password" ></td></tr><tr><td>生日</td><td><input type="text" name="birthday" ></td></tr><tr><td><input type="submit" value="注册"></td></tr></table>
</form>
</body>
</html>

Success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册成功</title>
</head>
<body>
<center>注册成功</center>
<center>你的生日是:<fmt:formatDate value="${requestScope.user.birthday }" pattern="yyyy年MM月dd日"/>
</center>
</body>
</html>

这时运行该程序,一定会出现数据转换异常,String类型不能转换为Date类型,这时需要写一个数据转换的实现类

package org.amuxia.tools;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;import org.springframework.core.convert.converter.Converter;public class ConverterToDate implements Converter<String,Date>{private String dataConverter;public void setDataConverter(String dataConverter) {this.dataConverter = dataConverter;}@Overridepublic Date convert(String date) {// TODO Auto-generated method stubSimpleDateFormat sdf = new SimpleDateFormat(this.dataConverter);try {return sdf.parse(date);} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}}

然后我们需要在spring配置文件中将该类注册,并自定义转换格式,配置文件如下:

这时再进行注册的提交,就不会报格式转换异常的错误了。

这里说明一下,<mvc:annotation-driven></mvc:annotation-driven>是spring使用标签配置简化了配置内容,他会自动注册处理器映射器和处理器适配器,同时它也会注册一个默认的数据转换Bean(ConversionService),但是我们这里是自定义的转换类,所以需要显示定义conversionService去覆盖它提供的默认实现类。

2,使用自定义编辑器转换数据

使用自定义编辑器转换数据类型,方法是在Controller类中使用@InitBinder注解来添加自定义的编辑器,这是spring对JavaBeans中的PropertyEditor的支持,引入的包是java.beans.PropertyEditorSupport

下面使用@InitBinder来实现日期格式的转换

自定义的转换类继承PropertyEditorSupport类:

package org.amuxia.tools;import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;public class DataEeitor extends PropertyEditorSupport{@Overridepublic void setAsText(String text) throws IllegalArgumentException {// TODO Auto-generated method stubSimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");Date date;try {date = sdf.parse(text);setValue(date);} catch (java.text.ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}

接着在Controller中增加一个方法initBinder(),使用@InitBinde注解,他会在Controller初始化时注册属性编辑器,该方法的参数用于处理请求消息和处理方法的绑定,将数据传入自定义的转换类进行数据的转换。该方法定义如下:

其余代码和第一种数据转换的实现方法一样,测试结果相同,同样实现了数据类型的转换。

3,注册全局自定义编辑器转换数据

这种实现方法和第二种很像,都是使用自定义编辑器来实现数据类型的转换,不同点是它实现了WebBindingInitializer接口,它不需要在每个Controller中使用@InitBinder注解了,而是在配置文件中进行全局的配置,定义的转换器全局可用。

下面使用WebBindingInitializer来完成数据格式的转换

首先定义一个WebBindingInitializer的实现类:

package org.amuxia.tools;import java.util.Date;import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;
public class GlobalBinder implements WebBindingInitializer{@Overridepublic void initBinder(WebDataBinder binder, WebRequest request) {// TODO Auto-generated method stubbinder.registerCustomEditor(Date.class, new DataEeitor());}}

接着定义自定义转换器DataEeitor,与第二种转换使用到的转换器一样,这里不再写。

最后在spring的配置文件中配置全局的转换器:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"><property name="webBindingInitializer"><bean class="org.amuxia.tools.GlobalBinder"></bean></property>
</bean>

三种数据类型转换器的优先级

对同一个类型的对象,可以用以上任何一种数据转换器来转换他的数据类型,不仅如此,还可以三种一起装配进去,如果装配了三种转换器,springMVC会根据以下顺序查找对应的编辑器:

1,查询通过@InitBinder装配的自定义转换器

2,查询通过ConversionService装配的自定义转换器

3,查询全局WebBindingInitializer自定义编辑器

以上用到的Demo地址:http://download.csdn.net/detail/weixin_36380516/9903746

springMVC数据格式转换的三种实现相关推荐

  1. html color 转换,Color颜色转换的三种方式(c#)

    Color颜色转换 1.在.net中如何把一个色名称转换成HTML色? System.Drawing.Color color = System.Drawing.Color.White; string ...

  2. python 图片和二进制转换的三种方式

    PIL格式转二进制 先读取为PIL格式,再转为二进制 import io import base64 from PIL import Imagedef image2byte(image):'''图片转 ...

  3. C# 对象与JSON字符串互相转换的三种方式

    JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式. 关于内存对象和JSON字符串的相互转换,在实际项目中应比较广泛,经过一番搜索,找到如下 ...

  4. C++内码转换的三种方法

    我们平时常见的三种中文内码是:GB2312(简体中文).GBK.BIG5(繁体中文).网上有很多中文内码的专用转换工具.我们碰到由于内码不一致而导致的乱麻问题,用这些工具可以进行相互转换.但论坛里经常 ...

  5. php 数据类型转换强制转换的三种方式

    (int).(integer):转换成整形 (float).(double).(real):转换成浮点型 (string):转换成字符串 (bool).(boolean):转换成布尔类型 (array ...

  6. c语言位操作大小写转换,C语言实现大小写转换的三种方法

    今天心血来潮,总结了下大小写转换的方法,大致有三种. 1.使用C语言提供的函数:toupper(),tolower() 使用这两个函数需要引入头文件:#include 示例代码: #include # ...

  7. NAT地址转换的三种实现方式

    NAT:不仅解决了IP地址不足的问题,而且还能隐藏内部网络的细节,避免来自网络外部的***,起到一定的安全作用.. NAT地址转换有三种实现方式: 静态地址转换:是将内部网络的私有IP地址转换为合法的 ...

  8. Excel常用技巧—数字和文本转换,三种方法任你选!!

    Excel图表系列: Excel数据分析常用函数①--查询函数 Excel数据分析常用函数②--统计函数 Excel数据分析常用函数③--字符串函数 Excel数据分析常用函数④--日期函数 Exce ...

  9. string和wstring之间转换的三种方法

    方法1 #include <string> #include <locale> #include <codecvt>//convert string to wstr ...

最新文章

  1. SAP MM 按采购订单查询付款信息的报表?
  2. 文本处理相关资料整理
  3. 日志分析logstash插件-grok详解
  4. 如何扩展CentOS7的SWAP分区
  5. PHPUNIT 单元测试
  6. IT架构的本质:工作12年,我的五点感悟
  7. POJ1107 ZOJ1042 UVALive2291 W's Cipher【密码+模拟】
  8. ffmpeg源码分析:transcode()函数
  9. 《深入理解计算机网络》读后小记 8、IP地址和子网
  10. java常见基础面试题
  11. php获取多选框的值
  12. 中国行政区划编码-省市县镇村
  13. java.exe 0xc000012d_应用程序无法正常启动 0xc000012d
  14. 服务器外链图片不显示,nginx服务器设置图片防盗链,禁止图片外链
  15. python爬取拉钩网招聘信息
  16. FFmpeg视频处理入门教程----从安装到使用(Linux版)
  17. 小伙用Python 分析了 20 万场吃鸡数据
  18. 无边的爱浸湿了我的心
  19. 漏洞修复:Often Misused: Weak SSL Certificate
  20. WebGL渲染错误:GL_INVALID_FRAMEBUFFER_OPERATION: Draw framebuffer is incomplete

热门文章

  1. 《诛仙Ⅰ》票房破3亿 QQ阅读《诛仙》小说全平台收入增长11.7倍
  2. 苹果的倔强!今秋新iPhone外观设计将与2018年款非常相似
  3. Facebook去年从中国获50亿美元广告收入 占营收10%
  4. 请查收~微信春节聊天彩蛋 微信群的卖萌小神器
  5. MiniGUI编程--编辑框
  6. npm ERR! code E404 npm ERR! 404 Not Found - GET https://registry.npmjs.com/@mlamp%2fuser-info-dropdo
  7. 无向简单图怎么判断_bfs----判断无向简单图中任意两点是否连通
  8. 遇到一个gcc编译器版本导致的运行结果有差异的问题
  9. 点阵字体显示系列之一:ASCII码字库的显示
  10. Mybatis if 判断等于一个字符串