返回介绍

6.2 Formatter

发布于 2025-04-22 20:10:00 字数 4256 浏览 0 评论 0 收藏

Formatter 就像 Converter 一样,也是将一种类型转换成另一种类型。但是,Formatter 的源类型必须是一个 String,而 Converter 则适用于任意的源类型。Formatter 更适合 Web 层,而 Converter 则可以用在任意层中。为了转换 Spring MVC 应用程序表单中的用户输入,始终应该选择 Formatter,而不是 Converter。

为了创建 Formatter,要编写一个实现 org.springframework.format.Formatter 接口的 Java 类。下面是这个接口的声明:

public interface Formatter<T>

这里的 T 表示输入字符串要转换的目标类型。该接口有 parse 和 print 两个方法,所有实现都必须覆盖它们。

T parse(String text, java.util.Locale locale)
String print(T object, java.util.Locale locale)

parse 方法利用指定的 Locale 将一个 String 解析成目标类型。print 方法与之相反,它返回目标对象的字符串表示法。

例如,formatter-demo 应用程序中用一个 LocalDateFormatter 将 String 转换成 Date。其作用与 converter-demo 中的 StringToLocalDateConverter 一样。

DateFormatter 类如清单 6.5 所示。

清单 6.5 Local DateFormatter 类

package formatter;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter; 
import java.time.format.DateTimeParseException; 
import java.util.Locale;
import org.springframework.format.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 String print(LocalDate date, Locale locale) {
    return date.format(formatter);
  }
  @Override
  public LocalDate parse(String s, Locale locale) 
      throws ParseException {
     try {
       return LocalDate.parse(s,
           DateTimeFormatter.ofPattern(datePattern));
     } catch (DateTimeParseException e) {
       // the error message will be displayed in <form:errors>
       throw new IllegalArgumentException(
           "invalid date format. Please use this pattern\""
               + datePattern + "\"");
    }
  }
}

为了在 Spring MVC 应用程序中使用 Formatter,需要利用名为 conversionService 的 bean 对它进行注册。bean 的类名称必须为 org.springframework.format.support.FormattingConversion ServiceFactoryBean。这与 converter-demo 中用于注册 converter 的类不同。这个 bean 可以用一个 formatters 属性注册 formatter,用一个 converters 属性注册 converter。清单 6.6 展示了 formatter-demo 的 Spring 配置文件。

清单 6.6 formatter-demo 的 Spring 配置文件

< ?xml version="1.0" encoding="UTF-8"?>
< beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

  < context:component-scan base-package="controller"/>
  < context:component-scan base-package="formatter"/>

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

  < mvc:resources mapping="/css/ **" location="/css/"/>
  < mvc:resources mapping="/ *.html" location="/"/>

  < bean id="viewResolver"
      class="org.springframework.web.servlet.view.
→InternalResourceViewResolver">
    < property name="prefix" value="/WEB-INF/jsp/" />
    < property name="suffix" value=".jsp" />
  < /bean>

  < bean id="conversionService"
      class="org.springframework.format.support.
→FormattingConversionServiceFactoryBean">
   < property name="formatters">
      < set>
        < bean class="formatter.LocalDateFormatter">
          < constructor-arg type="java.lang.String"
            value="MM-dd-yyyy" />
        < /bean>
      < /set>
    < /property>
  < /bean>
< /beans>

注意,还需要给这个 Formatter 添加一个 component-scan 元素。

在浏览器中打开下面的 URL,可以测试 app06b 中的 Formatter:

http://localhost:8080/formatter-demo/add-employee

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。