gpt4 book ai didi

java - 如何使用 Spring MVC 配置特定于 Controller 的字段格式化程序?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:25:07 24 4
gpt4 key购买 nike

我的应用程序中有一个名为 Foo 的数据类型,它看起来像这样:

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

// unique business key
private String businessKey;

...
}

此类型在整个 Web 应用程序中以多种形式使用,通常您希望使用 id 属性来回转换它,因此我实现了一个 Spring3 格式化程序来执行此操作并注册了该格式化程序全局 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());
}
...
}

这正是我想要的,但这是 2009 年的预览文档,它看起来不像 registerFormatter 方法已进入最终发布的 API。

你应该怎么做?

最佳答案

在我们的应用程序中,我们为此使用了 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());
}
});
}

关于java - 如何使用 Spring MVC 配置特定于 Controller 的字段格式化程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18431036/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com