Struts2 s:iterator 指令全面解析:遍历数组、List与Map

"这篇内容主要总结了Struts2框架中`s:iterator`标签的常见应用场景,包括遍历数组、列表(List)以及映射(Map)。在列表遍历中,区分了两种不同情况,而在映射遍历中则涉及四种不同的处理方式。"
在Struts2中,`s:iterator`标签是用于迭代集合数据的重要标签,它允许我们方便地遍历数组、列表或映射,并在页面上展示其内容。以下是对标题和描述中提到的知识点的详细说明:
一、遍历数组
在Java中,我们可以创建一个数组并将其存储在请求作用域中,然后在JSP页面中使用`s:iterator`进行遍历。以下是一个例子:
```jsp
<%
String[] arr_str = new String[]{"a", "b", "c", "d"};
request.setAttribute("arr_str", arr_str);
%>
<!-- 遍历数组 -->
<s:set name="arr_str" value="#request.arr_str"/>
<s:iterator value="#arr_str" id="itStr">
<s:property value="itStr"/>
</s:iterator>
<br/><hr/>
```
这段代码首先在服务器端创建了一个字符串数组,并将其存入请求对象。然后在JSP页面中,`s:set`标签设置了一个变量`arr_str`,指向请求中的数组。`s:iterator`标签遍历这个数组,每次迭代时,`s:property`标签会输出当前元素的值。
二、遍历一个List,里面存放的是Bean
在实际应用中,我们经常需要遍历包含对象的列表。这里以一个包含`Interest` Bean的列表为例:
```jsp
public class ActionInterest extends ActionSupport {
private ArrayList<Interest> inList;
// getters and setters...
public String execute() throws Exception {
inList = new ArrayList<>();
Interest in1 = new Interest("swim", "swimisgood");
Interest in2 = new Interest("run", "runisgood");
inList.add(in1);
inList.add(in2);
return SUCCESS;
}
// Interest类的定义...
}
<!-- 遍历一个list,里面的内容是一个bean -->
<s:iterator value="inList" id="interest">
<s:property value="#interest.fav"/> - <s:property value="#interest.desc"/><br/>
</s:iterator>
```
在Action类中,我们创建了一个`Interest`类型的列表,并填充了数据。在JSP页面中,`s:iterator`遍历列表,每次迭代时,`s:property`标签可以访问到Bean的属性,如`fav`和`desc`。
三、遍历Map
对于Map,有四种常见的遍历方式:
1. 遍历Map的所有键(keys)
2. 遍历Map的所有值(values)
3. 遍历Map的键值对(entry set)
4. 自定义排序遍历Map
例如,遍历键值对:
```jsp
Map<String, String> myMap = new HashMap<>();
myMap.put("key1", "value1");
myMap.put("key2", "value2");
<!-- 遍历Map的键值对 -->
<s:iterator value="myMap.entrySet()" var="entry">
Key: <s:property value="#entry.key"/>, Value: <s:property value="#entry.value"/><br/>
</s:iterator>
```
这段代码首先创建了一个Map,然后使用`s:iterator`遍历其entry set。在每次迭代中,我们可以访问到键(key)和值(value)。
以上就是关于Struts2框架中`s:iterator`标签的常用情况总结,包括数组、列表和映射的遍历。理解这些用法有助于更好地在Struts2应用程序中处理和展示数据。
相关推荐









神奇的技术宅
- 粉丝: 0
最新资源
- 水淼文件批量处理器:高效管理多媒体与文档
- 贷款违约预测模型:相关性分析与策略建议
- JPetStore6 Web Demo项目源码解析
- Bullet3与cocos2dx结合测试3D物理引擎示例
- Python项目毕业设计CapstoneProject指南
- 设计装置:弯曲抗浮锚杆桩头钢筋支墩技术文档
- 9013心率模块简易测试程序指南
- eWebEditor JSP在线文本编辑器功能介绍
- SONIX产品开发库IClib-V4.50安装包介绍
- React应用开发入门与项目脚本使用指南
- 探索JPetStore源码及工具在Web Demo项目中的应用
- libpng-1.5.14:全面的PNG图片处理库与二维码生成工具集成
- 印刷机校正专用平台设计装置行业文档
- 分布式爬虫技术实践:Python实现详解
- C#压缩包子GAME15738-ILP2开发详解
- 解决Ldap分页问题的实用方法