如何在Spring Controller中从一个表单中保存多个相同的实体?

时间:2014-04-10 12:27:04

标签: java spring spring-mvc

我有一个问题,如何在Spring Controller中从一个表单中保存多个相同的实体? 如果我在html中有以下代码:

<form method="post" action="/dictionary/save">
<table>
... BEGIN jsp foreach function ...
<tr>
  <td><input type=hidden name="id" value="${entity.id}"></td>
  <td><input type=text name="en" value="${entity.en}"></td>
  <td><input type=text name="lv" value="${entity.lv}"></td>
  <td><input type=text name="ru" value="${entity.ru}"></td>
</tr>
... END jsp foreach function ...
</table>
<input type=submit value="Save">
</form>

在JSP列表中可以直到50个实体。如何在一个请求中保存所有内容?

1 个答案:

答案 0 :(得分:1)

创建一个域对象的modelAttribute说..字典,它将包含一些元素的列表(你说在JSP中可以是50)

在JSP中,使用表单中的modelAttribute:form tag

而不是输入类型使用:

在春天

class Dictionary{ 
   @Id     @GeneratedValue(strategy = GenerationType.AUTO)
   private int id;

   @Column(unique = true, nullable = false)
   private String code;

   @Column
   private String ru;

   @Column
   private String lv;

   @Column
   private String en;
}

在控制器

List<Dictionary> diction=new ArrayList<Dictionary>();
model.addattribute("dictionary",diction);

在JSP中

<form:form method="post" action="/dictionary/save" modelAttribute="dictionary">
<table><tr>
<td>
<form:input path="diction["+rowNum+"].code" />
<form:input path="diction["+rowNum+"].ru" />
<form:input path="diction["+rowNum+"].lv" />
<form:input path="diction["+rowNum+"].en" />
</td>

//code to add next td (either through javascript or jquery)
</form:form>

* 请注意 1.标签不能在javascript或jquery中工作,你可以将简单的输入标签作为*

<input type="text" name="code"/>

此名称输入可以是您想要的任意数量