SpringMVC之类型转换

时间:2024-04-29 04:24:18

  在数据绑定上,SpringMVC提供了到各种基本类型的转换,由前端到后台时,SpringMVC将字符串参数自动转换为各种基本类型。而对于其他,则需要自己编写代码进行转换。本随笔以转换时间类型为例,使用三种方式进行实现(其实是两种):

一、使用Converter

  转换器必须实现Converter接口,该接口原型如下:

public interface Converter<S, T> {
T convert(S source);
}

  编写DateConverter,该转换器可以自定义转换格式,默认为年-月-日:

public class DateConverter implements Converter<String, Date> {

    private String pattern = "yyyy-MM-dd";

    public void setPattern(String pattern) {
this.pattern = pattern;
} @Override
public Date convert(String source) {
if (source == null || source.trim().isEmpty())
return null;
DateFormat format = new SimpleDateFormat(pattern);
Date date = null;
try {
date = format.parse(source.trim());
} catch (ParseException e) {
}
return date;
} }

  接下来是注册该转换器:

<mvc:annotation-driven conversion-service="conversionService" />

<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="cn.powerfully.demo.web.controller.DateConverter" />
</set>
</property>
</bean>

二、使用WebBindingInitializer与Editor实现局部转换

  在需要实现转换的Controller添加如下代码即可实现转换,该方法采用Editor进行转换,它能够将String类型转换为其他类型

@InitBinder
public void initBinder(WebDataBinder binder, WebRequest request) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

三、使用WebBindingInitializer与Editor实现全局转换

  编写WebBindingInitializer的实现类

public class BindingInitializer implements WebBindingInitializer {
@Override
public void initBinder(WebDataBinder binder, WebRequest request) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
PropertyEditor propertyEditor = new CustomDateEditor(dateFormat , true);
binder.registerCustomEditor(Date.class, propertyEditor );
}
}

  在springmvc配置文件中注册WebBindingInitializer

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer">
<bean class="cn.powerfully.demo.web.controller.BindingInitializer" />
</property>
</bean>

  特别注意的是:该bean必须定义在<mvc:annotation-driven />之前,否则无法生效。当然了,也可以使用注解方式:

@ControllerAdvice
public class WebBinder {
@InitBinder
public void initBinder(WebDataBinder binder){
binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm"));
}
}

总结:

  使用Converter能够将任意类型转换成其他类型。而是用Editor,则只能将String类型(前端接受到的数据)转换为其他类型。