六、List綁定java
List須要綁定在對象上,而不能直接寫在Controller方法的參數中。app
public class User { jsp
private String firstName; post
private String lastName; spa
。。。 code
} orm
public class UserListForm { 對象
private List users; get
。。。 input
}
@RequestMapping("test.do")
public void test(UserListForm userForm) {
for (User user : userForm.getUsers()) {
System.out.println(user.getFirstName() + " - " + user.getLastName());
}
}
<</span>form action="test.do" method="post">
<</span>table>
<</span>thead>
<</span>tr>
<</span>th>First Name</</span>th>
<</span>th>Last Name</</span>th>
</</span>tr>
</</span>thead>
<</span>tfoot>
<</span>tr>
<</span>td colspan="2"><</span>input type="submit" value="Save" /></</span>td>
</</span>tr>
</</span>tfoot>
<</span>tbody>
<</span>tr>
<</span>td><</span>input name="users[0].firstName" value="aaa" /></</span>td>
<</span>td><</span>input name="users[0].lastName" value="bbb" /></</span>td>
</</span>tr>
<</span>tr>
<</span>td><</span>input name="users[1].firstName" value="ccc" /></</span>td>
<</span>td><</span>input name="users[1].lastName" value="ddd" /></</span>td>
</</span>tr>
<</span>tr>
<</span>td><</span>input name="users[2].firstName" value="eee" /></</span>td>
<</span>td><</span>input name="users[2].lastName" value="fff" /></</span>td>
</</span>tr>
</</span>tbody>
</</span>table>
</</span>form>
其實,這和第4點User對象中的contantInfo數據的綁定有點相似,可是這裏的UserListForm對象裏面的屬性被定義成List,而不是普通自定義對象。因此,在JSP中須要指定List的下標。值得一提的是,Spring會建立一個以最大下標值爲size的List對象,因此,若是JSP表單中有動態添加行、刪除行的狀況,就須要特別注意,譬如一個表格,用戶在使用過程當中通過屢次刪除行、增長行的操做以後,下標值就會與實際大小不一致,這時候,List中的對象,只有在jsp表單中對應有下標的那些纔會有值,不然會爲null,看個例子:
<</span>form action="test.do" method="post">
<</span>table>
<</span>thead>
<</span>tr>
<</span>th>First Name</</span>th>
<</span>th>Last Name</</span>th>
</</span>tr>
</</span>thead>
<</span>tfoot>
<</span>tr>
<</span>td colspan="2"><</span>input type="submit" value="Save" /></</span>td>
</</span>tr>
</</span>tfoot>
<</span>tbody>
<</span>tr>
<</span>td><</span>input name="users[0].firstName" value="aaa" /></</span>td>
<</span>td><</span>input name="users[0].lastName" value="bbb" /></</span>td>
</</span>tr>
<</span>tr>
<</span>td><</span>input name="users[1].firstName" value="ccc" /></</span>td>
<</span>td><</span>input name="users[1].lastName" value="ddd" /></</span>td>
</</span>tr>
<</span>tr>
<</span>td><</span>input name="users[20].firstName" value="eee" /></</span>td>
<</span>td><</span>input name="users[20].lastName" value="fff" /></</span>td>
</</span>tr>
</</span>tbody>
</</span>table>
</</span>form>
這個時候,Controller中的userForm.getUsers()獲取到List的size爲21,並且這21個User對象都不會爲null,可是,第2到第19的User對象中的firstName和lastName都爲null。打印結果:
aaa - bbb
ccc - ddd
null - null
null - null
null - null
null - null
null - null
null - null
null - null
null - null
null - null
null - null
null - null
null - null
null - null
null - null
null - null
null - null
null - null
null - null
eee - fff