在 Struts2 中,表單可以一次提交多筆同類資料。若後端需要接收物件陣列,可透過命名規則 users[index].field 讓框架自動完成綁定。
先定義一個 User 類別,包含 id、username、sex、email、password 等欄位,並提供 getter 與 setter。
package com.example.entity;
public class User {
private Integer id;
private String username;
private String sex;
private String email;
private String password;
private int count;
// getters and setters
}在頁面中用迴圈產生多組輸入欄位,name 使用 users[0]、users[1] 這類格式。
<form action="linuxidc" method="post">
<% for (int i = 0; i < 2; i++) { %>
<input type="text" name="users[<%=i%>].username" />
<input type="text" name="users[<%=i%>].sex" />
<input type="text" name="users[<%=i%>].email" />
<input type="text" name="users[<%=i%>].password" />
<% } %>
<input type="submit" value="提交" />
</form>在 Action 中宣告 List<User> 型別的 users 屬性,並提供 getter 與 setter,Struts2 便會依表單欄位名稱完成注入。
public class LinuxidcAction extends ActionSupport {
private List<User> users;
public String execute() throws Exception {
for (User user : users) {
System.out.println(user.getUsername());
}
return Action.SUCCESS;
}
public List<User> getUsers() { return users; }
public void setUsers(List<User> users) { this.users = users; }
}這種寫法的關鍵在於表單欄位命名與 Action 屬性名稱一致,框架就能把多筆輸入轉成物件集合。