本文研究的主要是struts框架中復選框的相關內容。復選框在web開發中用的非常廣泛,具體介紹如下。
案例
如下圖,當前為用戶選中的水果為"香蕉",點擊按鈕,跳轉到修改界面進行修改。
跳轉到修改界面后要回顯用戶的選擇(香蕉),然后由用戶再次進行勾選,如圖:
前臺界面:
1
2
3
4
5
6
7
8
9
10
|
<body> <form action= "checboxaction_test.action" method= "post" > 請選擇您喜歡的水果:<br> <input type= "checkbox" name= "fruits" value= "香蕉" />香蕉 <input type= "checkbox" name= "fruits" value= "雪梨" />雪梨 <input type= "checkbox" name= "fruits" value= "西瓜" />西瓜</br> <input type= "submit" value= "跳轉到修改界面進行修改" > </form> </body> |
后臺checboxaction.java代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
public class checboxaction extends actionsupport { private static final long serialversionuid = 1l; /*前臺通過復選框選中的水果名稱*/ private string fruits; public string getfruits() { return fruits; } public void setfruits(string fruits) { this.fruits = fruits; } public string test(){ /*沒去除空格之前*/ system.out.println(this.getfruits()); /*獲取從前臺穿過來的字符串(注:這里必須去除空格,因為傳過來的每個值之間除了有逗號分隔符之外還都有空格,但是通過trim()的方式是去不掉空格的)*/ //string fruitstr = this.getfruits().trim(); /*必須如是這般才能去掉空格*/ string fruitstr = this.getfruits().replaceall(" ", ""); system.out.println("去除空格之后的字符串:" + fruitstr); /*把字符串通過逗號分隔為一個字符串數組*/ string[] fruit = fruitstr.split(","); /*遍歷所有的值,把它們存到一個集合中*/ list<string> myfruits = new arraylist<string>(); for (int i=0; i<fruit.length; i++){ myfruits.add(fruit[i]); } /*把用戶選中的復選框存到map中發送到前臺*/ actioncontext.getcontext().put("myfruits", myfruits); /*模擬從數據庫中查出所有的值,在前臺展示,然后和用戶選中的進行匹配*/ list<string> list = new arraylist<string>(); list.add( "香蕉" ); list.add( "雪梨" ); list.add( "西瓜" ); actioncontext.getcontext().put( "list" , list); return this .success; } } |
注:復選框向后臺傳值,傳過去的是一個字符串,且帶有空格,所以必須去除空格,但是用trim()方法是去除不了的,使用trim()方法之后的效果。如下:
如圖,毫無效果!但是,我們可以使用replaceall()方法,去替代空格,效果如下:
另外為了在修改界面展示所有的復選框(水果),我們在action中模擬從數據庫中取出所有的值,然后和用戶選擇的復選框一起傳到修改界面。
修改界面:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<body> <form action= "checboxaction_test.action" method= "post" > 您選擇的水果:<br> <c:foreach items= "${list}" var= "list" > <input type= "checkbox" value= "${list}" <c:foreach items= "${myfruits}" var= "fr" > ${fr == list ? "checked" : "" } </c:foreach> />${list} </c:foreach> </br> <input type= "submit" value= "修改" /> </form> </body> |
注:修改界面比較復雜,首先是遍歷所有復選框(水果),在每個浮選中又使用一個foreach循環,去遍歷用戶選擇的所有復選框(水果),然后通過三目運算符去判斷當前復選框是否被用戶選中,如果匹配,就勾選。
總結
以上就是本文關于復選框和struts2后臺交互代碼詳解的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/lzm1340458776/article/details/29565779