springMVC数据格式转换的三种实现

来源:互联网 发布:淘宝宝贝去哪里点发货 编辑:程序博客网 时间:2024/05/22 09:39

在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;@Controllerpublic 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;    }    @Override    public 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 block    e.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{    @Override    public 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{    @Override    public 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