Struts 2 不使用索引的形式将参数绑定到集合

Struts 2 Form Bind Parameters To Collection Without Using Index

Struts版本:2.3.16.3

有没有办法在不指定索引的情况下填充对象列表?目前我必须像这样引用集合:

<input name="myCollection[0].myProperty" value="some value" />

我真的很想做这样的事情:

<input name="myCollection[].myProperty" value="some value" />

我正在使用 JavaScript 在页面上动态添加和删除元素,使用 JavaScript 获得正确的索引一直很痛苦。而只是让后端按照元素从表单中出现的顺序添加到集合的末尾。类似于 PHP 处理它的方式。

parameters interceptor say that it is really just a ognl expression that the input name is binding to. I went to the ognl docs 的文档,它说您可以像这样引用数组:

array["length"]

这将是数组中的下一个元素。参数拦截器吐出一条消息,表明它正在拒绝此参数名称。我真的很想找到一种方法来实现这一点,即使这意味着扩展参数拦截器。

嗯,自从

  1. 您正在使用 Javascript
  2. 操纵页面
  3. 您在添加/删除元素时无法检测/更新元素的索引

最简单的解决方案是:

  1. 在操作它们时使用您喜欢的语法,例如 myCollection[].myProperty
  2. 在预提交功能中将它们转换成Struts 所需的形式

这样你就不必在操作元素时费心索引了,但只需一次,在最后,你可以简单地按名称或其他东西循环它们,并用 [=43= 更改它们的名称] 通过分配正确的索引。

jQuery的启动示例:

$(function() {
  $('#myform').submit(function() {
    $('[name^="myCollection[]"]').each(function(index) {
      var oldV = this.name;
      var newV = oldV.replace("myCollection[]", "myCollection[" + index + "]");
      console.log("was: " + oldV + " - now is: " + newV);
      this.name = newV;
    });
    return false;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myform">
  Open Javascript Console, then press submit, then inspect input elements
  <br>
  <input name="myCollection[].myProperty" />
  <br>
  <input name="myCollection[].myProperty" />
  <br>
  <input name="myCollection[].myProperty" />
  <br>
  <input name="myCollection[].myProperty" />
  <br>
  <input name="myCollection[].myProperty" />
  <br>
  <button>submit</button>
</form>

您需要以某种方式识别某些 属性 属于哪个对象。索引是最简单的方法,因此您不能只删除它们。

有很多方法可以实现您想要的。使用 javascript.

查看 Andrea 的一种可能解决方案的答案

您还可以将对象属性拉到简单列表中,然后将它们设置为对象。

例如

private List<String> myProperty;

可以在JSPw/o索引中引用:

<input name="myProperty" value="first value" />
<input name="myProperty" value="second value" />

当然,如果你有很多属性,你需要以某种方式同步它们在JSP中,这样列表中属性的顺序和大小是一致的每 属性.