Person.jsp (struts.xml中省略)
package com.mzy.entity;
public class Person {
private String name;
private String sex;
private int age;
public Person() {
super();
}
public Person(String name, String sex, int age) {
super();
this.name = name;
this.sex = sex;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", sex=" + sex + ", age=" + age + "]";
}
}
TagPersonAction.java
package com.mzy.tag;
import java.util.ArrayList;
import java.util.List;
import com.mzy.entity.Person;
import com.opensymphony.xwork2.ActionSupport;
public class TagPersonAction extends ActionSupport{
private static final long serialVersionUID = 7351425024147100121L;
List<Person> persons;
public List<Person> getPersons() {
return persons;
}
public void setPersons(List<Person> persons) {
this.persons = persons;
}
public String execute() {
persons = new ArrayList<Person>();
String name = "aaa";
int age = 10;
String sex;
for (int i=0 ;i<10; i++) {
name = name + i;
age += i;
if (i%2 == 0) {
sex = "男";
} else {
sex = "女";
}
persons.add(new Person(name, sex, age));
}
return SUCCESS;
}
}
jsp中:
<%@ 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>Person list start here!</title>
</head>
<body>
<table cellspacing="0" border="1">
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<!--
注意:
这里不写var的时候,默认是压入值栈中的!但是压入 值栈的每一次的person
默认都是iterator本身去取,当然也可以使用property去取值,但是有个地方出错了!!!
Person已经是在外面了!!
所以不是person.name 而是 name
不是person.age 而是age
... ...
如果是第一层,直接取值;如果是JavaBean的对象,直接Ognl直接会使用getter方法取值!
在使用struts的iterator循环时,不写var只会压到值栈中,写了var会在ActionContext中也压一份!
值栈中的每次的person对象,会被iterator在每次循环结束之后,从值栈中pop出来,但是ActionContext
的话,就是每次覆盖前一次,最后会保留最后一次的Person对象在ActionContext中!
-->
<s:iterator value="persons" var="person" status="s">
<%-- <s:debug></s:debug> --%>
<%-- <s:property/> --%>
<%-- <s:property/> --%>
<%-- <s:if test='#person.sex=="男"'> --%>
<s:if test='sex=="男"'>
<tr <s:if test="#s.odd">style="background-color:pink"</s:if>>
<td>
<%-- <s:property value="#person.name"/> --%>
<s:property value="name"/>
</td>
<td>
<%-- <s:property value="#person.sex"/> --%>
<s:property value="sex"/>
</td>
<td>
<%-- <s:property value="#person.age"/> --%>
<s:property value="age"/>
</td>
</tr>
</s:if>
</s:iterator>
<%-- <s:debug></s:debug> --%>
</table>
</body>
</html>