【问题标题】:Bind a PropertyEditor to all fields of a list?将 PropertyEditor 绑定到列表的所有字段?
【发布时间】:2013-02-01 16:03:50
【问题描述】:

在我的 Spring 3.1.2 应用程序中,我有一个包含对象列表的表单,这些对象将在表单中呈现为表格。我想将属性编辑器绑定到列表的一个字段,并且还有许多其他字段共享该类型。

我正在尝试使用registerCustomEditor(Class, String, PropertyEditor) 方法进行绑定,但它不起作用。我可以绑定到具有该类的所有字段,但这不符合我的需要。我试过使用fieldName*.fieldName 作为参数。如何绑定到列表中对象上的所有字段?

【问题讨论】:

  • 你能用多态来解决这个问题吗?将一个突出部分分解为它自己的类,然后使用该类注册 PropertyEditor。
  • @CodeChimp 我想我可以,但在这一点上并不可取。
  • 好吧,如果 registerCustomEditor 中的“字段”与我见过的所有其他 Spring MVC 内容相同,比如绑定错误,都需要一个完全限定的字段名称。因此,如果您在表单 bean 中使用列表,则第一个元素看起来类似于“formBean.listName[0]”。
  • @CodeChimp 是的,我刚刚实现了一个 hack,它通过循环将验证器添加到多行。不是一个很好的解决方案,但它确实有效。

标签: spring-mvc model-binding propertyeditor


【解决方案1】:

我在InitBinder 中写了一点小技巧,以找到所有适当的属性并将PropertyEditor 添加到每个属性中:

@InitBinder("detailForm")
protected void initBinder(WebDataBinder binder, WebRequest request) throws Exception {
    for (String param : request.getParameterMap().keySet()){
        if (param.endsWith("currencyAmount")){
            binder.registerCustomEditor(BigDecimal.class, param, new CurrencyPropertyEditor());
        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    相关资源
    最近更新 更多