关闭

struts--批量封装对象

标签: strutsimportinputactionclassdate
2332人阅读 评论(1) 收藏 举报
分类:

Struts1.2应用-批量封装对象

                                                                      ++YONG原创,转载请注明

1.    批量发布产品信息效果图: 

上图为批量发布产品页面。

上图为显示刚批量发布的产品页面。

2.    具体实现:

2.1.    域模型对象:Product.java

package org.qiujy.domain;

 

import java.sql.Date;

 

/**

 * 产品---实体域模型类

 * @author qiujy

 * @version 1.0

 */

public class Product {

    private Long id;

    private String name;

    private double price;

    private Date pubTime = new Date(new java.util.Date().getTime());

 

    public Product() {

    }

 

    public Product(Long id, String name, double price, Date pubTime) {

        this.id = id;

        this.name = name;

        this.price = price;

        this.pubTime = pubTime;

    }

 

    /**

     * @return the id

     */

    public Long getId() {

        return id;

    }

 

    /**

     * @param id

     *            the id to set

     */

    public void setId(Long id) {

        this.id = id;

    }

 

    /**

     * @return the name

     */

    public String getName() {

        return name;

    }

 

    /**

     * @param name

     *            the name to set

     */

    public void setName(String name) {

        this.name = name;

    }

 

    /**

     * @return the price

     */

    public double getPrice() {

        return price;

    }

 

    /**

     * @param price

     *            the price to set

     */

    public void setPrice(double price) {

        this.price = price;

    }

 

    /**

     * @return the pubTime

     */

    public Date getPubTime() {

        return pubTime;

    }

 

    /**

     * @param pubTime

     *            the pubTime to set

     */

    public void setPubTime(Date pubTime) {

        this.pubTime = pubTime;

    }

}

在这个类中日期的类型用的是java.sql.Date,而不是java.util.Date。这是因为Struts 1.x不支持请求参数到java.util.Date的转换,归根到底是由于org.apache.commons.beanutils.ConvertUtilsBean.convert()不支持关于java.util.Date的转换。另外,值得注意的是common-beanutils是通过java.sql.Date.valueOf()方法工作的,所以在页面输入的字符串的格式必须为“yyyy-MM-dd”。

2.2.    创建一个自定义列表集合:

它继承自LinkedList类,重写get()方法,作用就是在Struts 1.x框架调用这个方法时,如果index超出列表大小,则会实例化新项放到列表中,避免出现(IndexOutOfBoundsException)异常。

package org.qiujy.common;

 

import java.util.LinkedList;

 

/**

 * 类说明: ActionForm中使用,以避免OutOfIndexException

 * 注意:不要在其他地方使用本类

 * @author qiujy

 * @version 1.0

 */

public class AutoInitArrayList extends LinkedList{

    /** 容器内保存的类 */

    private Class clazz;

   

    /**私有构造函数,保证外界无法直接实例化*/

    private AutoInitArrayList() {

    }

   

    public AutoInitArrayList(Class clazz) {

        this.clazz = clazz;

    }

    /**

     * save the updates of customer types.

     */

    public Object get(int index) {

        try {

            if (super.size() < index + 1) {

                int cnt = index + 1 - super.size();

                for (int i = 0; i < cnt; i++) {

                    super.add(clazz.newInstance());

                }

            }

        } catch (InstantiationException e) {

            e.printStackTrace();

        } catch (IllegalAccessException e) {

            e.printStackTrace();

        }

        return super.get(index);

    }

}

2.3.    Struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

 

<struts-config>

  <data-sources />

  <form-beans >

    <form-bean name="batchWrappingForm" type="org.qiujy.web.struts.form.BatchWrappingForm" />

 

  </form-beans>

 

  <global-exceptions />

  <global-forwards />

  <action-mappings >

    <action

      attribute="batchWrappingForm"

      input="/batchWrapping.jsp"

      name="batchWrappingForm"

      path="/batchWrapping"

      scope="request"

      parameter="method"

      type="org.qiujy.web.struts.action.BatchWrappingAction">

         <forward name="toCurrent" path="/batchWrapping.jsp"/>

         <forward name="toList" path="/displayinfo.jsp"/>

      </action>

 

  </action-mappings>

 

  <message-resources parameter="org.qiujy.web.struts.ApplicationResources" />

</struts-config>

2.4.    Form Bean

package org.qiujy.web.struts.form;

 

import java.util.List;

 

import org.apache.struts.action.ActionForm;

import org.qiujy.common.AutoInitArrayList;

import org.qiujy.domain.Product;

 

/**

 * 批量封装示例Form Bean

 * @author qiujy

 * @version 1.0

 */

public class BatchWrappingForm extends ActionForm {

   

    private int optId; //操作ID

    private List products = new AutoInitArrayList(Product.class);

   

    public BatchWrappingForm(){

    }

    /**

     * @return the products

     */

    public List getProducts() {

        return products;

    }

 

    /**

     * @param products the products to set

     */

    public void setProducts(List products) {

        this.products = products;

    }

   

    /**

     * List中新增一个Product对象

     */

    public void addItem(){

       this.products.add(new Product());

    }

   

    /**

     * List中删除指定索引的Product对象

     * @param index

     */

    public void deleteItem(int index){

       int size = products == null ? 0 : products.size();

       if(index >=0 && index < size){

           this.products.remove(index);

       }

    }

 

    /**

     * @return the optId

     */

    public int getOptId() {

        return optId;

    }

 

    /**

     * @param optId the optId to set

     */

    public void setOptId(int optId) {

        this.optId = optId;

    }

}

2.5.    Action类:

package org.qiujy.web.struts.action;

 

import java.util.List;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.actions.DispatchAction;

import org.qiujy.web.struts.form.BatchWrappingForm;

 

/**

 * 批量封装示例Action

 * @author qiujy

 * @version 1.0

 */

public class BatchWrappingAction extends DispatchAction {

 

    /**

     * 保存所有的产品

     * @param mapping

     * @param form

     * @param request

     * @param response

     * @return

     */

    public ActionForward saveAll(ActionMapping mapping, ActionForm form,

            HttpServletRequest request, HttpServletResponse response) {

        BatchWrappingForm batchWrappingForm = (BatchWrappingForm) form;

        List temp = batchWrappingForm.getProducts();

       

        request.setAttribute("products", temp);

       

        return mapping.findForward("toList");

    }

   

    /**

     * 新增一项

     * @param mapping

     * @param form

     * @param request

     * @param response

     * @return

     */

    public ActionForward addItem(ActionMapping mapping, ActionForm form,

            HttpServletRequest request, HttpServletResponse response) {

        BatchWrappingForm batchWrappingForm = (BatchWrappingForm) form;

       

        batchWrappingForm.addItem();

       

        return mapping.findForward("toCurrent");

    }

   

    /**

     * 删除当前项

     * @param mapping

     * @param form

     * @param request

     * @param response

     * @return

     */

    public ActionForward deleteItem(ActionMapping mapping, ActionForm form,

            HttpServletRequest request, HttpServletResponse response) {

        BatchWrappingForm batchWrappingForm = (BatchWrappingForm) form;

       

        batchWrappingForm.deleteItem(batchWrappingForm.getOptId());

       

        return mapping.findForward("toCurrent");

    }

}

2.6.    输入页面:batchWrapping.jsp

<%@ page language="java" pageEncoding="utf-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

<html>

    <head>

        <title>批量封装对象示例</title>

        <script type="text/javascript">

        <!--

            function setParamValue(parameter, value) {

                if (document.getElementById(parameter) != undefined) {

                    document.getElementById(parameter).value = value;

                }

            }

        //-->

        </script>

    </head>

    <body>

        <h2 align="center">批量封装对象示例</h2>

        <hr/>

        <form action="batchWrapping.do" method="post">

        <input type="hidden" name="method" value="saveAll">

        <input type="hidden" name="optId">

        <table border="0" width="680px" align="center">

            <tr style="background-color: powderblue; font-weight: bold;">

                <td width="30%">产品名</td>

                <td width="20%">价格</td>

                <td width="30%">生产日期</td>

                <td width="20%">操作</td>

            </tr>

<c:forEach var="prod" items="${batchWrappingForm.products}" varStatus="status">

            <tr>

                <td >

    <input name="products[${status.index}].name" value="${prod.name}"/>

                </td>

                <td>

    <input name="products[${status.index}].price" value="${prod.price}"/>

                </td>

                <td>

<input name="products[${status.index}].pubTime" value="<fmt:formatDate value='${prod.pubTime}' type='date'/>"/>

                </td>

                <td>

<input type="button" value="删除此列" onclick="javascript:setParamValue('optId', '${status.index }');setParamValue('method', 'deleteItem'); this.form.submit();"/>

                </td>

            </tr>

</c:forEach>

            <tr style="background-color: powderblue;">

                <td colspan="4" align="center">

                    <input type="submit" value=" 提交 " />&nbsp;

                    <input type="submit" value=" 重置 " />&nbsp;&nbsp;

                    <input align="center" type="button" value="新增一列" onclick="javascript:setParamValue('method', 'addItem'); this.form.submit();"/>

                </td>

            </tr>

        </table>

        </form>

    </body>

</html>

本页面中,最关键的地方是组装<input>的元素名称,Struts 1.2对名称格式类似“xxx[9].xx”的请求,会进行封装。

2.7.    最终显示页面:displayinfo.jsp

<%@ page language="java" pageEncoding="utf-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

<html>

    <head>

        <title>显示批量封装的对象</title>

    </head>

    <body>

        <h2 align="center">显示批量封装的对象</h2>

        <hr />

        <table border="0" width="680px" align="center">

            <tr style="background-color: powderblue; font-weight: bold;">

                <td width="10%">序号</td>

                <td width="35%">产品名</td>

                <td width="20%">价格</td>

                <td width="35%">生产日期</td>

            </tr>

            <c:forEach var="prod" items="${products}" varStatus="status">

                <tr>

                    <td><c:out value="${status.count}" /></td>

                    <td><c:out value="${prod.name}" /></td>

                    <td><c:out value="${prod.price}" /></td>

                    <td><fmt:formatDate value='${prod.pubTime}'/></td>

                </tr>

            </c:forEach>

        </table>

    </body>

</html>

 

3.    参考文档:

http://www.blogjava.net/max/archive/2006/12/08/86439.html

4.    本例源代码:

      

 
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1365297次
    • 积分:9585
    • 等级:
    • 排名:第1975名
    • 原创:130篇
    • 转载:20篇
    • 译文:0篇
    • 评论:1098条