第一步:首先,在product包下新建Product.java文件,内 容如下:
package product;
import java.io.Serializable;
import java.util.Date;
/**
* 产品持久化类
* @author lijunjie
*
*/
public class Product implements Serializable {
private String name;
private double price;
private Date dateOfProduction;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Date getDateOfProduction() {
return dateOfProduction;
}
public void setDateOfProduction(Date dateOfProduction) {
this.dateOfProduction = dateOfProduction;
}
}
第二步:然后,在同上的包下添加ProductConfirm.java类,代码 如下
package product;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
/**
* 商品确认类
* @author lijunjie
*
*/
public class ProductConfirm extends ActionSupport {
private List<Product> products;
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
@Override
public String execute() throws Exception {
for(Product p : products){
System.out.println(p.getName()+"--"+p.getPrice()+"--"+p.getDateOfProduction());
}
return SUCCESS;
}
}
第三步:再在struts.xml文件中配置ProductConfirm Action:
<package name="product" extends="struts-default">
<action name="ProductConfirm" class="product.ProductConfirm">
<result>/showproducts.jsp</result>
</action>
</package>
第四步:在WebRoot下新建addproduct.jsp:
<%@page contentType="text/html;charset=UTF-8" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Add Product</title>
</head>
<body>
<s:form action="ProductConfirm" theme="simple">
<table>
<tr>
<td>商品名称</td>
<td>商品价格</td>
<td>生产日期</td>
</tr>
<s:iterator value="new int[3]" status="stat">
<tr>
<td><s:textfield name="%{'products['+#stat.index+'].name'}"/></td>
<td><s:textfield name="%{'products['+#stat.index+'].price'}"/></td>
<td><s:textfield name="%{'products['+#stat.index+'].dateOfProduction'}"/></td>
</tr>
</s:iterator>
<tr>
<td colspan="3"><s:submit value="提交"/></td>
</tr>
</table>
</s:form>
</body>
</html>
第五步:在WebRoot下新建showproducts.jsp:
<%@page contentType="text/html;charset=UTF-8" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>显示商品</title>
</head>
<body>
<table border="1">
<tr>
<td>商品名称</td>
<td>商品价格</td>
<td>生产日期</td>
</tr>
<s:iterator value="products" status="stat">
<tr>
<td><s:property value="name"/></td>
<td>$<s:property value="price"/></td>
<td><s:property value="dateOfProduction"/></td>
</tr>
</s:iterator>
</table>
</body>
</html>
运行结果如图:
在addproducts.jsp 的<s:textfield>的name为“%{'products['+#stat.index+'].name'} ”,% {exp}格式表示使用OGNL表达式,上述表达式的相当于<%= "products[" + stat.index + "].name" %>