前一篇文章已将详细讲解了基本数据类型、包装类以及集合类的相关的数据绑定。本文主要讲解的是数据绑定中的数据转换的内容,比如输入的是字符串,需要将字符串转化成SimpleDate类型的日期格式,这就需要用到类型转换。常见的类型转换的接口有PropertyEditor、Formatter、Converter等,这些接口通常用于自定义参数绑定,其中包含了参数格式的转换,比如日期的转换等,本文就通过日期的转换进行举例说明。
该接口一般用于局部使用,并且需要使用WebDataBinder对象为其注册,以控制初始的输入格式,然后解析出正确的时间格式。如下所示:
@RequestMapping(value = "date1")
@ResponseBody
public String date1(Date date1){
return date1.toString();
}
@InitBinder("date1")
public void initDate1(WebDataBinder binder){
binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd hh-mm-ss"),true));
}
由上可知,binder对象通过一个registerCustomEditor(requiredType, propertyEditor)方法第一个参数是需要转换成的类,后者表示一个propertyEditor对象来控制输入的格式,可以通过PropertyEditor的一个实现类CustomDateEditor来实现。
Formatter也可以用于格式转换,并且支持全局配置,因此,如果项目中的所有日期格式都要统一的话,就可以通过Formatter实现格式统一。而如果需要全局配置,则需要自己定义类实现Formatter接口,以下是实现类的代码,具体实现了其parse类:
import org.springframework.format.Formatter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MyDateFormatter implements Formatter {
public Date parse(String text, Locale locale) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(text);
}
public String print(Date object, Locale locale) {
return null;
}
}
实现了转换类之后,还需要在springmvc配置文件中对其进行全局配置。
首先进行包的配置:
然后将id配置到注释驱动之中,实现全局配置。
以下是Controller类中的方法:
@RequestMapping(value = "date2.do")
@ResponseBody
public String date2(Date date2){
return date2.toString();
}
测试结果:
以下来检测一下全局性,由于前面date1是局部的,现在对Formatter的配置是全局的,按理说全局配置中再进行局部配置的话,当前局部配置可以覆盖当前原先的配置。为了区分两者,前面有意让两者输入格式稍有不同。
现在将date1的@initBinder注释取消,即取消了局部配置,获取如下测试结果,可以看出取消局部配置,那么date1对象也在全局配置下,因此格式符合全局配置的格式要求:
Converter的实现方式与formatter类似,首先先实现一个Converter类:
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyDateConverter implements Converter {
public Date convert(String source) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
然后进行配置:
然后运行项目,键入url,得到如下:
以上三种方法都能实现数据转换以及绑定,但是稍有不同。
1.PropertyEditor只支持局部使用,需要WebdataBinder对象协助;而后两个则可以局部和全局使用。
2.PropertyEditor和Formatter内部可扩展,但是Converter内部不可扩展。