复选框和Struts2后台交互代码详解

2025-05-29 0 95

本文研究的主要是struts框架中复选框的相关内容。复选框在web开发中用的非常广泛,具体介绍如下。

案例

如下图,当前为用户选中的水果为"香蕉",点击按钮,跳转到修改界面进行修改。

复选框和Struts2后台交互代码详解

跳转到修改界面后要回显用户的选择(香蕉),然后由用户再次进行勾选,如图:

复选框和Struts2后台交互代码详解

前台界面:

?

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()方法之后的效果。如下:

复选框和Struts2后台交互代码详解

如图,毫无效果!但是,我们可以使用replaceall()方法,去替代空格,效果如下:

复选框和Struts2后台交互代码详解

另外为了在修改界面展示所有的复选框(水果),我们在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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 复选框和Struts2后台交互代码详解 https://www.kuaiidc.com/112672.html

相关文章

发表评论
暂无评论