上一个博客中索道数据绑定,但是要在Spring正确绑定数据需要用到转换器(Converter)和格式化(Formatter)。
Converter是通用原件,可以在应用程序的任意层中使用。
Formatter是专门为Web层设计的。
Converter
Converter可以将一种类型转换成另一种类型的对象。为了创建Converter,必须实现org.springframework.core.converter.Converter接口的一个java类。
public interface Converter<S,T>
s表示源类型,T表示目标类型。
一下代码是可以把String转换成LocalDate数据类型的程序。
public class StringToLocalDateConverter implements Converter<String, LocalDate> {
private String datePattern;
public StringToLocalDateConverter(String datePattern) {
this.datePattern = datePattern;
}
@Override
public LocalDate convert(String s) {
try{
return LocalDate.parse(s, DateTimeFormatter.ofPattern(datePattern));
}catch(DateTimeParseException e) {
throw new IllegalArgumentException("invalid date format. please user this pattern\"" + datePattern + "\"");
}
}
}
为了使用Spring MVC应用程序中定制的Converter,需要在Spring MVC配置文件中编写名为conversionService的bean。bean的类名必须为org.springframework.context.support.ConversionServiceFactoryBean。这个bean必须包含一个converters属性,它将列出要在应用程序中使用的所有定制Converter。之后要给annotation-driven元素的conversion-service属性赋值bean名称。
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="converter.StringToLocalDateConverter">
<constructor-arg type="java.lang.String" value="MM-dd-yyyy"/>
</bean>
</list>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService"/>Formatter
Formatter也是将一种类型转换成另一种类型。但是Formatter的源类型必须是String,而Converter则适用于任意的源类型。Formatter更适合Web层,Converter可以在任意层使用。为了转换Spring MVC应用程序表单中的用户输入,始终应该选择Formatter,而不是Converter。
使用FormatterRegistrar注册Formatter
public class MyFormatterRegistrar implements FormatterRegistrar {
private String datePattern;
public MyFormatterRegistrar(String datePattern){
this.datePattern = datePattern;
}
@Override
public void registerFormatters(FormatterRegistry registry){
registry.addFormatter(new LocalDateFormatter(datePattern));
}
}有了Registrar,就不需要在Spring MVC配置文件中注册任何Formatter了,只在Spring配置文件中注册Registrar就可以了
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService" class="org.springframework.format.support.FormattinConversinoServiceFactoryBean">
<property name="formatterRegistrars">
<list>
<bean class="formatter.MyFormatterRegistrar">
<constructor-arg type="java.lang.String" value="MM-dd-yyyy"/>
</bean>
</list>
</property>
</bean>选择Converter,还是Formatter
Converter是一般工具,可以将一种类型转换成另一种类型。
Formatter只能将String转换成另一种java类型。
所以在Web层上Formatter更合适。

京公网安备 11010502036488号