以下,來自於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程序中推薦使用