小编典典

Spring数字格式化与数字列表上的registercustomereditor

spring-mvc

在spring注册customerEditor以使用给定的numberFormat实例格式化数字时,很容易将其应用于jsp中的特定字段,例如:

NumberFormat numberFormat = getNumberFormat(0, 0, 2);
PropertyEditor propertyEditor = 
    new CustomNumberEditor(Double.class, numberFormat, true);
binder.registerCustomEditor(Double.class, "myDoubleField", propertyEditor);

这将根据应用程序的语言环境(关于千位/小数分隔符的逗号和点)以及分隔符前后的指定小数位数,得出正确的数字格式。

但是,如果我有一个未知大小的列表,其中包含双打,如何以一种聪明的方式格式化它们?我当然可以遍历该列表,并为列表中的每个条目注册一个,但是这看起来既麻烦又错误。

由于spring绑定到带有标记的列表,所以字段名称将具有类似"myDoubleField[0] .... myDoubleField[n]"这样的名称,因此很难…

有一个简单的解决方法吗?还是根本没有解决方法?

在此先多谢,希望有人能指出正确的方向!


阅读 553

收藏
2020-06-01

共1个答案

小编典典

通过使用全局PropertyEditorRegistrar来代替旧的繁琐的注册自定义编辑器的方法来解决。在构造函数中初始化控制器:

public myController(PropertyEditorRegistrar customPropertyEditorRegistrar) {
    this.customPropertyEditorRegistrar = customPropertyEditorRegistrar;
}

并在initBinder中注册:

@Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)   throws Exception {
    customPropertyEditorRegistrar.registerCustomEditors(binder);
}

强制以CustomerPropertyEditorRegistrar中指定的方式格式化所有元素。
例如。双打:

public final class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {
    // Double
    PropertyEditor doubleEditor = getLocaleBasedNumberEditor(Double.class, true);
    registry.registerCustomEditor(double.class, doubleEditor);
    registry.registerCustomEditor(Double.class, doubleEditor);
}

如果特定字段需要其他格式,则可以用旧的方式覆盖特定字段。

//蹄

2020-06-01