当前位置: 首页 > 教程 > Struts2 >

Struts2 <s:iterator>迭代器标签示例

精华
小牛编辑
146浏览
2023-03-14

Struts2迭代器标签用来迭代一个值,它可以是任何 java.util.Collection 或 java.util.Iterator的值。在本教程中,您将创建一个列表变量,使用迭代器标签来遍历,并得到使用IteratorStatus迭代状态。

这里创建一个Web工程:strut2iterator,来演示在多个复选框如何设置的默认值,整个项目的结构如下图所示:

1. 动作

Action类有列表属性,它包含多种美味 “KFC combo meals”.

IteratorKFCAction

package com.yiibai.common.action;
 
import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;
 
public class IteratorKFCAction extends ActionSupport{
 
	private List<String> comboMeals;
	
	public List<String> getComboMeals() {
		return comboMeals;
	}

	public void setComboMeals(List<String> comboMeals) {
		this.comboMeals = comboMeals;
	}

	public String execute() {
		
		comboMeals = new ArrayList<String>();
		comboMeals.add("Snack Plate");
		comboMeals.add("Dinner Plate");
		comboMeals.add("Colonel Chicken Rice Combo");
		comboMeals.add("Colonel Burger");
		comboMeals.add("O.R. Fillet Burger");
		comboMeals.add("Zinger Burger");
		
		return SUCCESS;
	}
}

2. 迭代器 - Iterator示例

下面的JSP页面使用iterator标签来遍历显示所有的“肯德基组合餐”名单。 在迭代器标签,它包含了一个“status”的属性,它用于在IteratorStatus类中声明名称。

IteratorStatus类用于获取有关迭代的状态信息。支持属性索引,计数,第一个,最后,奇,偶和等。
<%@ taglib prefix="s" uri="/struts-tags" %>
 
<html>
<head>
</head>
 
<body>
<h1>Struts2 <s:iterator>标签示例</h1>

<div><div class="ads-in-post hide_if_width_less_800">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 728x90 - After2ndH4 -->
<ins class="adsbygoogle hide_if_width_less_800" 
     
     data-ad-client="ca-pub-2836379775501347"
     data-ad-slot="3642936086"
	 data-ad-region="yiibairegion"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div></div><h2>Simple Iterator</h2>
<ol>
<s:iterator value="comboMeals">
  <li><s:property /></li>
</s:iterator>
</ol>

<h2>Iterator with IteratorStatus</h2>
<table>
<s:iterator value="comboMeals" status="comboMealsStatus">
  <tr>
  	<s:if test="#comboMealsStatus.even == true">
      <td ><s:property/></td>
    </s:if>
    <s:elseif test="#comboMealsStatus.first == true">
      <td><s:property/> (This is first value) </td>
    </s:elseif>
    <s:else>
      <td><s:property/></td>
    </s:else>
  </tr>
</s:iterator>
</table>

</body>
</html>

3. struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>

 	<constant name="struts.devMode" value="true" />
	
	<package name="default" namespace="/" extends="struts-default">
	
		<action name="iteratorKFCAction" 
			class="com.yiibai.common.action.IteratorKFCAction" >
			<result name="success">/pages/iterator.jsp</result>
		</action>
		
	</package>
		
</struts>

4. 示例

http://localhost:8080/struts2iterator/iteratorKFCAction.action


参考

  1. Struts2 <s:Iterator>标签示例
  2. IteratorStatus文档

下载代码 -  http://pan.baidu.com/s/1gdx02fp