与JSTL标准标签库的c:forEach类似的,struts也提供了一个s:iterator用于遍历一个集合中的数据
- 为ProductAction增加list方法
1. 为ProductAction增加一个products属性,类型是List,并提供getter setter
2. 为ProductAction增加一个list()方法,为products添加3个product对象,并返回“list"
package com.how2java.action; import java.util.ArrayList; import java.util.List; import com.how2java.bean.Product; public class ProductAction { private Product product; private List<Product> products; public List<Product> getProducts() { return products; } public void setProducts(List<Product> products) { this.products = products; } public String show() { product = new Product(); product.setName("iphone7"); return "show"; } public String add() { return "show"; } public String list() { products=new ArrayList(); Product p1 = new Product(); p1.setId(1); p1.setName("product1"); Product p2 = new Product(); p2.setId(2); p2.setName("product2"); Product p3 = new Product(); p3.setId(3); p3.setName("product3"); products.add(p1); products.add(p2); products.add(p3); return "list"; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } }
- struts.xml
配置路径listProduct,并返回list.jsp
<?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.i18n.encoding" value="UTF-8"></constant> <package name="basicstruts" extends="struts-default"> <action name="showProduct" class="com.how2java.action.ProductAction" method="show"> <result name="show">show.jsp</result> </action> <action name="addProduct" class="com.how2java.action.ProductAction" method="add"> <result name="show">show.jsp</result> </action> <action name="listProduct" class="com.how2java.action.ProductAction" method="list"> <result name="list">list.jsp</result> </action> </package> </struts>
- list.jsp
使用s:iterator标签进行遍历
value 表示集合
var 表示遍历出来的元素
st 表示遍历出来的元素状态
st.index 当前行号 基0
st.count 当前行号 基1
st.first 是否是第一个元素
st.last 是否是最后一个元素
st.odd 是否是奇数
st.even 是否是偶数
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%> <%@ taglib prefix="s" uri="/struts-tags"%> <%@page isELIgnored="false"%> <style> table { border-collapse: collapse; } td { border: 1px solid gray; } </style> <table align="center"> <tr> <td>id</td> <td>name</td> <td>st.index</td> <td>st.count</td> <td>st.first</td> <td>st.last</td> <td>st.odd</td> <td>st.even</td> </tr> <s:iterator value="products" var="p" status="st"> <tr> <td>${p.id}</td> <td>${p.name}</td> <td>${st.index}</td> <td>${st.count}</td> <td>${st.first}</td> <td>${st.last}</td> <td>${st.odd}</td> <td>${st.even}</td> </tr> </s:iterator> </table>
- 测试
重启tomcat,访问网页
http://127.0.0.1:8080/struts/listProduct