以下,来自于Springmvc指南第二版,第93页。
Spring的Formatter是可以将一种类型转为另一种类型。
例如用户输入的date类型可能有多种格式。
下面是才用 registrar方式注册formatter
比如:在controller中接收一个LocalDate。
@RequestMapping("/test")
public String test(@RequestParam(required = false) LocalDate date){
System.out.println("date = " + date);
return null;
}
注意:LocalDate,比较特殊点,不能new,前面必须要用 required=false,不用的话,spring会试图去new一个LocalDate,然后就会引发异常。
自定义Formatter:
public class LocalDateFormatter implements Formatter<LocalDate>{
private DateTimeFormatter formatter;
private String datePattern;
public LocalDateFormatter(String datePattern) {
this.datePattern = datePattern;
formatter = DateTimeFormatter.ofPattern(datePattern);
}
@Override
public LocalDate parse(String s, Locale locale) throws ParseException {
try {
return LocalDate.parse(s, DateTimeFormatter.ofPattern(datePattern));
}catch (Exception e){
e.printStackTrace();
throw e;
}
}
@Override
public String print(LocalDate localDate, Locale locale) {
return localDate.format(formatter);
}
}
FormatterRegistrar:
public class MyFormatterRegistrar implements FormatterRegistrar{
private String datePattern;
public MyFormatterRegistrar(String datePattern) {
this.datePattern = datePattern;
}
@Override
public void registerFormatters(FormatterRegistry formatterRegistry) {
formatterRegistry.addFormatter(new LocalDateFormatter(datePattern));
}
}
dispatcher-servlet.xml
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatterRegistrars">
<set>
<bean class="registrar.MyFormatterRegistrar">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd"/>
</bean>
</set>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService"/>
直接注册formatter,不同registrar
dispatcher-servlet.xml
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatters">
<set>
<bean class="formatter.LocalDateFormatter">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd"/>
</bean>
</set>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService"/>
Formatter和Converter,都能转换类型
Converter是一种类型转换另一种,可以用在很多层中
Formatter是String转换另一种,适用于web层,springmvc程序中推荐使用