【问题标题】:better way for dynamic forms with Spring?使用 Spring 获取动态表单的更好方法?
【发布时间】:2009-05-20 21:04:57
【问题描述】:

我想知道在使用 SpringMVC 和 Spring 表单时是否有更简单/更好的方式来处理动态表单(通过 js 向 dom 添加表单项)?

具有包含许多 LineItems 的 Invoice 对象的图像。

public class Invocie {
    private List LineItems;

    public Invoice() {
        lineItems = ListUtils.lazyList(new ArrayList<LineItem>(), FactoryUtils.instantiateFactory(LineItem.class));
    }
}

显示属于我当前使用的发票的项目

<forEach items="${invoice.lineItems}" varStatus="i">
  <form:input path="lineItems[${i.index}].productName" />
</c:forEach>

要添加 LineItems,我有一些计算新索引并将其添加到 DOM 的 js。删除 LineItem 时,我目前必须重新编号所有索引,这是我想避免的部分,有可能吗?

【问题讨论】:

  • 好吧,我不想这么说,但是有没有办法让 Spring Controller 接受 PHP 接受的内容,我的意思是把 [] 放在路径中?

标签: java spring spring-mvc


【解决方案1】:

我已经实现了一个教程,可以帮助您在客户端使用 jQuery 和 Springs AutoPopulating 列表来解决这个问题。

http://eggsylife.co.uk/2009/11/30/spring-forms-dynamic-lists-and-ajax/

编辑 来自 Webarchive 的链接https://web.archive.org/web/20160729163958/http://eggsylife.co.uk/2009/11/30/spring-forms-dynamic-lists-and-ajax/

【讨论】:

  • @eggsy84 动态删除对象怎么样?
【解决方案2】:

你可以使用以下

public class InvoiceController extends SimpleFormController {

    protected void initBinder(HttpServletRequest request, ServletRequetDataBinder binder) throws Exception {
        binder.registerCustomEditor(List.class, "lineItems", new CustomCollectionEditor(List.class)() {
            protected Object convertElement(Object lineItem) {
                LineItem li = (LineItem) lineItem;

                // StringUtils is a jakarta Commons lang static class
                return (StringUtils.isBlank(li.getProductName())) ? null : li;
            }

        });
    }

}

然后在 onBind 方法中,您根据以下内容删除空引用:

protected void onBind(HttpServletRequest request, Object command, BindException bindException) throws Exception {
    Invoice invoice = (Invoice) command;

    invoice.getLineItems().removeAll(Collections.singletonList(null));
}    

问候,

【讨论】:

  • 他们确实走在一起。这个问题并不是真正的问题,我想知道是否有比 apache commons 的lazyList 更好的方法。
【解决方案3】:

我发现在 JSP 中添加/设置项目时,还需要使用 GrowthList 进行装饰以避免一些错误。 (还创建了一个自定义的 SpringList impl。基本上做了双重装饰。)

lineItems = GrowthList.decorate(ListUtils.lazyList(new ArrayList<LineItem>(), FactoryUtils.instantiateFactory(LineItem.class)));

我同意。问题当然是删除项目。

您可以在 html 中使用 spring marker 语法。因此,如果您使用 javascript 从列表中删除一个项目(例如在索引 2 处),那么您将使用以下标记该索引:

<input type="hidden" name="_lineItems[2]">

然后当提交表单时,spring 会看到标记并为 lineItems2 放入一个空项(基于惰性列表工厂),而不是忽略它。

【讨论】:

    【解决方案4】:

    我今天一直在努力解决这个问题,并想出了here 描述的一些解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-08
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多