熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

Struts 1.x中批量封裝對象

2022-06-13   來源: Java開源技術 

  批量發布產品信息頁面輸出如下圖所示

  圖1 發布產品 發布產品

  圖2 查看產品
查看產品

  具體實現

  首先創建代表產品的類 Productjava代碼如下

    package tipsAndTricks;

  import javasqlDate;

  public class Product  {

  private String name;

  private double price;

  private Date dateOfProduction;

  public Date getDateOfProduction()  {

  return dateOfProduction;

  }

  public void setDateOfProduction(Date dateOfProduction)  {

  this dateOfProduction = 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;

  }

  }

  package tipsAndTricks;

  import javasqlDate;

  public class Product  {

  private String name;

  private double price;

  private Date dateOfProduction;

  public Date getDateOfProduction()  {

  return dateOfProduction;

  }

  public void setDateOfProduction(Date dateOfProduction)  {

  this dateOfProduction = 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;

  }

  }

  本例子中的dateOfProduction屬性使用了javasqlDate而不是javautilDate這是因為Struts x不支持請求參數到javautilDate的轉換歸根到底是由於monsbeanutilsnvert()不支持關於javautilDate的轉換另外值得注意的是commonbeanutils是通過javasqlDatevalueOf()方法工作的所以在頁面輸入的字符串的格式必須為yyyyMMdd

  實現上述功能大概有三種方法下面我會分別對兩種方法進行詳細的講述

  方法一動態表單(Dynamic Actoin Form)+ 數組
    首先讓我們來看一下Struts的配置文件WEBINF/strutsconfigxml內容如下

  view plaincopy to clipboardprint?
    <? xml version= encoding=UTF ?>

  <! DOCTYPE strutsconfig PUBLIC //Apache Software Foundation//DTD Struts Configuration //EN config__dtd >

  < strutsconfig >

  < datasources />

  < formbeans >

  < formbean name =dynaProductsForm

  type =orgapachestrutsactionDynaActionForm >

  < formproperty name =products

  type =tipsAndTricksProduct[] size = />

  </ formbean >

  </ formbeans >

  < globalexceptions />

  < globalforwards />

  < actionmappings >

  < action attribute =dynaProductsForm input =/addProductsjsp

  name =dynaProductsForm path =/batchWrappingWithArray

  scope =request type =tipsAndTricksBatchWrappingWithArrayAction

  validate =false >

  < forward name =success path =/viewProductsjsp />

  </ action >

  </ actionmappings >

  < messageresources parameter =tipsAndTricksApplicationResources />

  </ strutsconfig >

  <? xml version= encoding=UTF ?>

  <! DOCTYPE strutsconfig PUBLIC //Apache Software Foundation//DTD Struts Configuration //EN config__dtd >

  < strutsconfig >

  < datasources />

  < formbeans >

  < formbean name =dynaProductsForm

  type =orgapachestrutsactionDynaActionForm >

  < formproperty name =products

  type =tipsAndTricksProduct[] size = />

  </ formbean >

  </ formbeans >

  < globalexceptions />

  < globalforwards />

  < actionmappings >

  < action attribute =dynaProductsForm input =/addProductsjsp

  name =dynaProductsForm path =/batchWrappingWithArray

  scope =request type =tipsAndTricksBatchWrappingWithArrayAction

  validate =false >

  < forward name =success path =/viewProductsjsp />

  </ action >

  </ actionmappings >

  < messageresources parameter =tipsAndTricksApplicationResources />

  </ strutsconfig > 我想這些配置應該用不著怎麼解釋了有Struts x驗證的朋友對此都不會陌生因此接下來創建/addProductsjsp文件代碼如下

  view plaincopy to clipboardprint?
    <% @ page language = java pageEncoding = utf %>

  <% @ taglib uri = html prefix = html %>

  <% @ taglib uri = prefix = c %>

  <! DOCTYPE HTML PUBLIC //WC//DTD HTML Transitional//EN >

  < html >

  < head >

  < title > Add Products </ title >

  </ head >

  < body >

  < html:form action =/batchWrappingWithArray method =post >

  < table border = >

  < tr style =backgroundcolor:powderblue; fontweight:bold; >

  < td > Product Name </ td >

  < td > Price </ td >

  < td > Date of production </ td >

  </ tr >

  < c:forEach var =products items =${dynaProductsFormmapproducts} >

  < tr >

  < td >< html:text indexed =true name =products property =name /></ td >

  < td >< html:text indexed =true name =products property =price /></ td >

  < td >< html:text indexed =true name =products property =dateOfProduction /></ td >

  </ tr >

  </ c:forEach >

  < tr >

  < td colspan = >< html:submit /></ td >

  </ tr >

  </ table >

  </ html:form >

  </ body >

  </ html >

  <% @ page language = java pageEncoding = utf %>

  <% @ taglib uri = html prefix = html %>

  <% @ taglib uri = prefix = c %>

  <! DOCTYPE HTML PUBLIC //WC//DTD HTML Transitional//EN >

  < html >

  < head >

  < title > Add Products </ title >

  </ head >

  < body >

  < html:form action =/batchWrappingWithArray method =post >

  < table border = >

  < tr style =backgroundcolor:powderblue; fontweight:bold; >

  < td > Product Name </ td >

  < td > Price </ td >

  < td > Date of production </ td >

  </ tr >

  < c:forEach var =products items =${dynaProductsFormmapproducts} >

  < tr >

  < td >< html:text indexed =true name =products property =name /></ td >

  < td >< html:text indexed =true name =products property =price /></ td >

  < td >< html:text indexed =true name =products property =dateOfProduction /></ td >

  </ tr >

  </ c:forEach >

  < tr >

  < td colspan = >< html:submit /></ td >

  </ tr >

  </ table >

  </ html:form >

  </ body >

  </ html > 例中我使用了JSTL 如果大家還沒有嘗試過使用JSP 的JSTL和EL建議大家去看看相關文章上面的<c:forEach />的作用是到dynaProductsForm的map屬性中取出products數組並對其進行遍歷再依靠<html:text />標志將products的元素的屬性以輸入框的形式輸出<html:text />標志的屬性indexed=true則表示在輸出HTML時將<input>的命名為類似products[]name的名字

  然後再創建/viewProductsjsp頁面內容如下

  view plaincopy to clipboardprint?
    <% @ page language = java pageEncoding = utf %>

  <% @ taglib uri = prefix = c %>

  <! DOCTYPE HTML PUBLIC //WC//DTD HTML Transitional//EN >

  < html >

  < head >

  < title > View Products </ title >

  </ head >

  < body >

  < table border = >

  < tr style =backgroundcolor:powderblue; fontweight:bold; >

  < td > Product Name </ td >

  < td > Price </ td >

  < td > Date of production </ td >

  </ tr >

  < c:forEach var =product items =${products} >

  < tr >

  < td > ${productname} </ td >

  < td > ${productprice} </ td >

  < td > ${productdateOfProduction} </ td >

  </ tr >

  </ c:forEach >

  </ table >

  </ body >

  </ html >

  <% @ page language = java pageEncoding = utf %>

  <% @ taglib uri = prefix = c %>

  <! DOCTYPE HTML PUBLIC //WC//DTD HTML Transitional//EN >

  < html >

  < head >

  < title > View Products </ title >

  </ head >

  < body >

  < table border = >

  < tr style =backgroundcolor:powderblue; fontweight:bold; >

  < td > Product Name </ td >

  < td > Price </ td >

  < td > Date of production </ td >

  </ tr >

  < c:forEach var =product items =${products} >

  < tr >

  < td > ${productname} </ td >

  < td > ${productprice} </ td >

  < td > ${productdateOfProduction} </ td >

  </ tr >

  </ c:forEach >

  </ table >

  </ body >

  </ html > 我想這份也不多作說明不過大家可以通過上述代碼看出使用JSTL + EL的確比Struts x的logic + bean要方便和簡潔不僅如此EL還支持一定的運算符和函數操作

  最後是建立Action文件 BatchWrappingWithArrayActionjava代碼如下

  view plaincopy to clipboardprint?
    package tipsAndTricks;

  import javaxservlethttpHttpServletRequest;

  import javaxservlethttpHttpServletResponse;

  import orgapachestrutsactionAction;

  import orgapachestrutsactionActionForm;

  import orgapachestrutsactionActionForward;

  import orgapachestrutsactionActionMapping;

  import orgapachestrutsactionDynaActionForm;

  public class BatchWrappingWithArrayAction extends Action  {

  public ActionForward execute(ActionMapping mapping ActionForm form

  HttpServletRequest request HttpServletResponse response)  {

  DynaActionForm dynaProductsForm = (DynaActionForm) form;

  requestsetAttribute( products dynaProductsFormget( products ));

  return mappingfindForward( success );

  }

  }

  package tipsAndTricks;

  import javaxservlethttpHttpServletRequest;

  import javaxservlethttpHttpServletResponse;

  import orgapachestrutsactionAction;

  import orgapachestrutsactionActionForm;

  import orgapachestrutsactionActionForward;

  import orgapachestrutsactionActionMapping;

  import orgapachestrutsactionDynaActionForm;

  public class BatchWrappingWithArrayAction extends Action  {

  public ActionForward execute(ActionMapping mapping ActionForm form

  HttpServletRequest request HttpServletResponse response)  {

  DynaActionForm dynaProductsForm = (DynaActionForm) form;

  requestsetAttribute( products dynaProductsFormget( products ));

  return mappingfindForward( success );

  }

  } 此Action將動態表單傳過來的products數組放到request中轉到/viewProductsjsp發布運行應用程序在浏覽器的地址欄中輸入效果請參考如圖

  在/addProductsjsp的Date of production必須以(yyyyMMdd)的形式正確填寫且不能為空

  方法二表單(Actoin Form)+ 列表(List)
    方法一雖然簡單但是有一個明顯的缺點——數組的長度已經固定故我們不能在運行時通過程序設置對象數量下面將要介紹的方法可以很好地解決這個問題

  首先我們要創建類 AutoInitArrayListjava代碼如下

  view plaincopy to clipboardprint?
    package tipsAndTricks;

  import javautilArrayList;

  public class AutoInitArrayList < T > extends ArrayList < T >  {

  private static final long serialVersionUID = L ;

  private Class < T > t = null ;

  public AutoInitArrayList(Class < T > t)  {

  this t = t;

  }

  @Override

  public T get( int index)  {

  try  {

  while (index >= size())  {

  add(tnewInstance());

  }

  } catch (Exception e)  {

  eprintStackTrace();

  }

  return super get(index);

  }

  }

  package tipsAndTricks;

  import javautilArrayList;

  public class AutoInitArrayList < T > extends ArrayList < T >  {

  private static final long serialVersionUID = L ;

  private Class < T > t = null ;

  public AutoInitArrayList(Class < T > t)  {

  this t = t;

  }

  @Override

  public T get( int index)  {

  try  {

  while (index >= size())  {

  add(tnewInstance());

  }

  } catch (Exception e)  {

  eprintStackTrace();

  }

  return super get(index);

  }

  } AutoInitArrayList繼承ArrayList並重載get()方法作用就是在Struts x框架調用這個方法時如果index超出列表大小則會實例化新項放到列表中避免出現(IndexOutOfBoundsException)異常

  接著讓我們看Struts的配置內容如下

  view plaincopy to clipboardprint?
    <? xml version= encoding=UTF ?>

  <! DOCTYPE strutsconfig PUBLIC //Apache Software Foundation//DTD Struts Configuration //EN config__dtd >

  < strutsconfig >

  < datasources />

  < formbeans >

  < formbean name =dynaProductsForm

  type =orgapachestrutsactionDynaActionForm >

  < formproperty name =products

  type =tipsAndTricksProduct[] size = />

  </ formbean >

  < formbean name =normalProductsForm

  type =tipsAndTricksNormalProductsForm />

  </ formbeans >

  < globalexceptions />

  < globalforwards />

  < actionmappings >

  < action attribute =dynaProductsForm input =/addProductsjsp

  name =dynaProductsForm path =/batchWrappingWithArray

  scope =request type =tipsAndTricksBatchWrappingWithArrayAction

  validate =false >

  < forward name =success path =/viewProductsjsp />

  </ action >

  < action attribute =normalProductsForm input =/addProductsjsp

  name =normalProductsForm path =/batchWrappingNormal scope =request

  type =tipsAndTricksBatchWrappingNormalAction validate =false >

  < forward name =success path =/viewProductsjsp />

  </ action >

  </ actionmappings >

  < messageresources parameter =tipsAndTricksApplicationResources />

  </ strutsconfig >

  <? xml version= encoding=UTF ?>

  <! DOCTYPE strutsconfig PUBLIC //Apache Software Foundation//DTD Struts Configuration //EN config__dtd >

  < strutsconfig >

  < datasources />

  < formbeans >

  < formbean name =dynaProductsForm

  type =orgapachestrutsactionDynaActionForm >

  < formproperty name =products

  type =tipsAndTricksProduct[] size = />

  </ formbean >

  < formbean name =normalProductsForm

  type =tipsAndTricksNormalProductsForm />

  </ formbeans >

  < globalexceptions />

  < globalforwards />

  < actionmappings >

  < action attribute =dynaProductsForm input =/addProductsjsp

  name =dynaProductsForm path =/batchWrappingWithArray

  scope =request type =tipsAndTricksBatchWrappingWithArrayAction

  validate =false >

  < forward name =success path =/viewProductsjsp />

  </ action >

  < action attribute =normalProductsForm input =/addProductsjsp

  name =normalProductsForm path =/batchWrappingNormal scope =request

  type =tipsAndTricksBatchWrappingNormalAction validate =false >

  < forward name =success path =/viewProductsjsp />

  </ action >

  </ actionmappings >

  < messageresources parameter =tipsAndTricksApplicationResources />

  </ strutsconfig > 然後創建表單類 NormalProductsFormjava代碼如下

  view plaincopy to clipboardprint?
    package tipsAndTricks;

  import javautilList;

  import orgapachestrutsactionActionForm;

  public class NormalProductsForm extends ActionForm  {

  private List products = new AutoInitArrayList < Product > (Product class );

  public List getProducts()  {

  return products;

  }

  public void setProducts(List products)  {

  this products = products;

  }

  package tipsAndTricks;

  import javautilList;

  import orgapachestrutsactionActionForm;

  public class NormalProductsForm extends ActionForm  {

  private List products = new AutoInitArrayList < Product > (Product class );

  public List getProducts()  {

  return products;

  }

  public void setProducts(List products)  {

  this products = products;

  }

  } 接下來是Action類 BatchWrappingNormalActionjava代碼如下

  view plaincopy to clipboardprint?
      /**/ /*

  * Generated by MyEclipse Struts

  * Template path: templates/java/JavaClassvtl

  */

  package tipsAndTricks;

  import javaxservlethttpHttpServletRequest;

  import javaxservlethttpHttpServletResponse;

  import orgapachestrutsactionAction;

  import orgapachestrutsactionActionForm;

  import orgapachestrutsactionActionForward;

  import orgapachestrutsactionActionMapping;

  public class BatchWrappingNormalAction extends Action  {

  public ActionForward execute(ActionMapping mapping ActionForm form

  HttpServletRequest request HttpServletResponse response)  {

  NormalProductsForm normalProductsForm = (NormalProductsForm) form;

  requestsetAttribute( products normalProductsFormgetProducts());

  return mappingfindForward( success );

  }

  }

  /**/ /*

  * Generated by MyEclipse Struts

  * Template path: templates/java/JavaClassvtl

  */

  package tipsAndTricks;

  import javaxservlethttpHttpServletRequest;

  import javaxservlethttpHttpServletResponse;

  import orgapachestrutsactionAction;

  import orgapachestrutsactionActionForm;

  import orgapachestrutsactionActionForward;

  import orgapachestrutsactionActionMapping;

  public class BatchWrappingNormalAction extends Action  {

  public ActionForward execute(ActionMapping mapping ActionForm form

  HttpServletRequest request HttpServletResponse response)  {

  NormalProductsForm normalProductsForm = (NormalProductsForm) form;

  requestsetAttribute( products normalProductsFormgetProducts());

  return mappingfindForward( success );

  }

  } 基本上與方法一的Action一樣下面再看看新的輸入文件/addProductsjsp內容如下

  view plaincopy to clipboardprint?
    <% @ page language = java pageEncoding = utf %>

  <% @ taglib uri = html prefix = html %>

  <% @ taglib uri = prefix = c %>

  <! DOCTYPE HTML PUBLIC //WC//DTD HTML Transitional//EN >

  < html >

  < head >

  < title > Add Products </ title >

  </ head >

  < body >

  < html:form action =/batchWrappingNormal method =post >

  < table border = >

  < tr style =backgroundcolor:powderblue; fontweight:bold; >

  < td > Product Name </ td >

  < td > Price </ td >

  < td > Date of production </ td >

  </ tr >

  < c:forEach begin = end = var =i >

  < tr >

  < td >< input name =products[${i}]name /></ td >

  < td >< input name =products[${i}]price /></ td >

  < td >< input name =products[${i}]dateOfProduction /></ td >

  </ tr >

  </ c:forEach >

  < tr >

  < td colspan = >< html:submit /></ td >

  </ tr >

  </ table >

  </ html:form >

  </ body >

  </ html >

  <% @ page language = java pageEncoding = utf %>

  <% @ taglib uri = html prefix = html %>

  <% @ taglib uri = prefix = c %>

  <! DOCTYPE HTML PUBLIC //WC//DTD HTML Transitional//EN >

  < html >

  < head >

  < title > Add Products </ title >

  </ head >

  < body >

  < html:form action =/batchWrappingNormal method =post >

  < table border = >

  < tr style =backgroundcolor:powderblue; fontweight:bold; >

  < td > Product Name </ td >

  < td > Price </ td >

  < td > Date of production </ td >

  </ tr >

  < c:forEach begin = end = var =i >

  < tr >

  < td >< input name =products[${i}]name /></ td >

  < td >< input name =products[${i}]price /></ td >

  < td >< input name =products[${i}]dateOfProduction /></ td >

  </ tr >

  </ c:forEach >

  < tr >

  < td colspan = >< html:submit /></ td >

  </ tr >

  </ table >

  </ html:form >

  </ body >

  </ html > /addProductsjsp主要作用組裝<input>的元素名稱Struts x對名稱格式類似xxx[]xx的請求會進行封裝發布運行應用程序在浏覽器的地址欄中輸入效果請參考如圖


From:http://tw.wingwit.com/Article/program/Java/ky/201311/28917.html
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.