本文研究的主要是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
相关文章
猜你喜欢
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
- ASP.NET自助建站系统的域名绑定与解析教程 2025-06-10
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-29 49
-
2025-05-25 50
-
2025-05-25 35
-
2025-06-04 82
-
2025-05-25 49
热门评论





