不知道大家是否遇过这样情况,在一个页面里同时提交几个对象,例如,在发布产品的页面,同时发布几个产品.
package org.cric.model;
import java.util.Date;
/**
* 产品持久化类
* @author Administrator
*
*/
public class Product {
private String name;
private double price;
private Date createDate;
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 getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
package org.cric.action;
import java.util.List;
import org.cric.model.Product;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
public class ProductAction extends ActionSupport {
private List<Product> products;
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
//////////////////////////////////////
//////////////////////////////////////
public String execute() throws Exception
{
for(Product p:products){
System.out.println(p.getName()+"--"+p.getPrice()+"--"+p.getCreateDate());
}
return Action.SUCCESS;
}
}
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd" > <struts> <package name="product" extends="json-default"> <action name="addProduct" class="org.cric.action.ProductAction"> <result>/showproducts.jsp</result> </action> </package> </struts>
<s:form action="addProduct" 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+'].createDate'}"/></td>
</tr>
</s:iterator>
<tr>
<td colspan="3"><s:submit value="提交"/></td>
</tr>
</table>
</s:form>
<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="createDate"/></td> </tr> </s:iterator> </table>
在addProducts.jsp的<s:textfield>的name为%{'products['+stat.index+']'.name},%{exp}格式表示使用OGNL表达式,上述表达式的相对于<%="products["+stat.index+"].name"%>
本文介绍了一个使用Struts2框架实现的批量提交多个对象的例子。该例子通过一个表单允许用户输入多个产品的名称、价格及创建日期,并将这些数据封装到多个Product对象中,最终在后端打印出来。

955

被折叠的 条评论
为什么被折叠?



