*ineratorstatus对象介绍:
此类的对象封装了本次循环的相关信息,通过访问其属性获得,主要属性有:
index:当前循环到的集合的索引
count:已经循环的次数
first:是否为第一次循环
last:是否为最后一次循环
odd:当前位置是否为奇数
even:当前位置是否为偶数
eg:
新建类action1.java,代码如下:
package my.test; import com.opensymphony.xwork2.actionsupport; public class action1 extends actionsupport{ private string[] arr=new string[5]; //一定要添加get/set方法,否则会出现空指针异常 public string[] getarr() { return arr; } public void setarr(string[] arr) { this.arr = arr; } public string execute(){ int i=101; //下面的for循环的赋值不起作用 for(string a:arr){ a=""+i++; } arr[3]="this is 3";//这里验证上面的for循环对arr的赋值是不起作用的,这里由string数组和string的特性来决定,看运行结果即可 return success; } }
新建jsp文件/iterator.jsp,记得引入struts的标签
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>insert title here</title> </head> <body> <s:debug></s:debug> <s:iterator var="one" value="arr" begin="2" status="sta"> <!-- 由于循环到的值保存到值栈中,所以下面通过s:property标签取值 --> 循环到的值为:<s:property value="one"/><br> 循环的次数为:<s:property value="#sta.count"/><br> 循环的索引为:<s:property value="#sta.index"/><br> 是否为奇数:<s:property value="#sta.odd"/><hr> </s:iterator> </body> </html>
最后配置文件来一个:
<?xml version="1.0" encoding="utf-8" ?> <!doctype struts public "-//apache software foundation//dtd struts configuration 2.3//en" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.enable.dynamicmethodinvocation" value="false" /> <constant name="struts.devmode" value="true" /> <package name="test" namespace="/" extends="struts-default"> <action name="iterator" class="my.test.action1"> <result>/iterator.jsp</result> </action> <action name="index"> <result type="redirectaction"> <param name="actionname">helloworld</param> <param name="namespace">/example</param> </result> </action> </package> <!-- add packages here --> </struts>
笔者用的是struts2 2.3.30版本,不同版本的配置文件是不一样滴
运行一个:
