如何使用Spring MVC配置特定于控制器的字段格式化程序?

Jla*_*aud 9 java spring spring-mvc spring-3

我的应用程序中有一个名为Foo的数据类型,如下所示:

public class Foo {
  // synthetic primary key
  private long id; 

  // unique business key
  private String businessKey;

  ...
}
Run Code Online (Sandbox Code Playgroud)

此类型在整个Web应用程序中以多种形式使用,通常您希望使用该id属性来回转换它,因此我实现了Spring3 Formatter,并使用全局Spring转换服务注册该格式化程序.

但是,我有一个表单用例,我想用转换来转换businessKey.实现Formatter很容易实现,但是我怎么告诉Spring只为这个特定的表单使用该格式化程序呢?

我在http://static.springsource.org/spring/previews/ui-format.html上找到了一个文档,其中有一节关于注册特定于字段的格式化程序(在底部一直见5.6.6),它提供了这个示例:

@Controller
public class MyController {
  @InitBinder
  public void initBinder(WebDataBinder binder) {
    binder.registerFormatter("myFieldName", new MyCustomFieldFormatter());
  }        
  ...
}
Run Code Online (Sandbox Code Playgroud)

这正是我想要的,但是这是2009年的预览文档,它看起来并不像registerFormatter最终发布的API那样.

你怎么这么做的?

Kej*_*jml 2

在我们的应用程序中,我们使用PropertyEditorSupport类来实现此目的。处理日历的简单示例,但您可以用于任何自定义类,只需覆盖getAsText()setAsText()方法:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Calendar.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String value) {
            try {
                Calendar cal = Calendar.getInstance();
                cal.setTime(new SimpleDateFormat("dd-MM-yyyy").parse(value));
                setValue(cal);
            } catch (ParseException e) {
                setValue(null);
            }
        }

        @Override
        public String getAsText() {
            if (getValue() == null) {
                return "";
            }
            return new SimpleDateFormat("dd-MM-yyyy").format(((Calendar) getValue()).getTime());
        }
    });
}
Run Code Online (Sandbox Code Playgroud)