1. 程式人生 > >struts2 表單資料繫結map、list等

struts2 表單資料繫結map、list等

在Struts2中,Form的提交非常方便。

e.g: A 要在Action中取出頁面提交的username和password,兩個屬性同屬User物件,此時:

在Action中,宣告public User user;並給出get()和set();

在JSP中,

<input type="text" name="user.username"/>  或用標籤:<s:textfield name="user.username" label="使用者名稱"/> 
<input type="text" name="user.password"/>  或用標籤:<s:textfield name="user.password" label="密 碼"/>

這樣可將user物件的輸入值直接繫結到Action中。

e.g: B 然而,很多時候我們需要不不僅僅是一個物件,而是多個物件,List,Map,又或者Set。

先說 Map和List:

 如果 Action 中的屬性是 Map<String, User> users; 那麼與此對應的表單寫法就是:(用標籤來寫) 
            <s:textfield name="users['one'].username" label="第一個使用者名稱"/> 
            <s:textfield name="users['one'].password" label="第一個密碼"/> 
            <s:textfield name="users['two'].username" label="第二個使用者名稱"/> 
            <s:textfield name="users['two'].password" label="第二個密碼"/>

此時,繫結到Action中的就是一個Map型別的users["one","two"]

如果是對於 Action 中的  List 屬性,List<User> users; 那麼與此對應的表單寫法就是: 
            <s:textfield name="users[0].username" label="第一個使用者名稱"/> 
            <s:textfield name="users[0].password" label="第一個密碼"/> 
            <s:textfield name="users[1].username" label="第二個使用者名稱"/> 
            <s:textfield name="users[1].password" label="第二個密碼"/> 

此時,繫結到Action中的就是一個List型別的users[0,1]

e.g C 我們再來看看Set,set是一個無序集合,所以無法像 List 那樣用數字下標來訪問

此時提交頁面這麼寫,最好提交前能根據輸入的使用者名稱自動修動輸入框的 name。 
        使用者名稱: <input name="users('scott').username"/> 
        密 碼: <input name="users('scott').password"/> 
顯示的時候頁面可用標籤 
        使用者名稱: <s:property value="users('scott').username"/> 
        密 碼: <s:property value="users('scott').password"/> 

<input type="user.username" value="jack"> 
<input type="user.username" value="lucy"> 
action中取得username的值是"jack,lucy". 
注意:此處password是字串型別,不是陣列型別