java

位置:IT落伍者 >> java >> 浏览文章

Struts 1.x中批量封装对象


发布日期:2023年09月12日
 
Struts 1.x中批量封装对象

批量发布产品信息页面输出如下图所示

发布产品

查看产品

具体实现

首先创建代表产品的类 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的请求会进行封装发布运行应用程序在浏览器的地址栏中输入效果请参考如图

               

上一篇:Struts 配置与组件介绍

下一篇:Hibernate:HQL/QBC查询语言比较的用法