现在的位置: 首页 > 综合 > 正文

在STRUTS中如何处理查询的到的RESULTSET

2014年02月08日 ⁄ 综合 ⁄ 共 2558字 ⁄ 字号 评论关闭

STRUTS中如何处理查询的到的RESULTSET

http://www.code168.com/ShowArticle.asp?ArtClass=4&ArtID=3838

关于这个问题可能每个人有自己的解决办法。
但如果要按照struts的风格来做,应该是这样的:
1) 
自己写个类(假定为DataMap),这个类继承HashMap,并实现DynaBean
2) 
ResultSet中的数据取出填充到这个DataMap

3
)将多条数据(也就是多个DataMap)填到一个ArrayList
4) 
将这个ArrayList放到你的ActionForm

5
)在jsp中引用, 仿照 strutsexample中的例子引用。
例如:
<logic:iterate id="subscription" name="user" property="subscriptions">
<tr>
<td align="left">
<bean:write name="subscription" property="host" filter="true"/>
</td>
<td align="left">
<bean:write name="subscription" property="username" filter="true"/>
</td>
<td align="center">
<bean:write name="subscription" property="type" filter="true"/>
</td>
<td align="center">
<bean:write name="subscription" property="autoConnect"/>
</td>
</tr>
</logic:iterate>
这里subscriptions就是刚才讲的 那个ArrayList
user
ActionForm的名字

subscription
就是你那个DataMap的实例,代表一条记录
那些property实际上就是字段名了。
 
本贴对您是否有帮助? 投票:       投票结果:  0    0
 
 
-----------------------------------------------------------

看到很多朋友在问这个问题,我愿意再重复一遍。希望能对大家有用

下面是我在回答 "单选框如何用发表时间: 2003-3-10 下午7:20 "
时的参考代码,很有代表性。现略作改动(下面的所有代码都经过实际验证)

这是一个最小实现:

后台处理代码:
////////////////////////
ResultSet rs = ...
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
ArrayList rows = new ArrayList();
while(rs.next()) {
HashMap row = new HashMap();
for (int i = 1; i <= columnCount; i++) {
String name = rsmd.getColumnName(i);
row.put(name, rs.getObject(i));
}
rows.add(row);
}
///////////////////////////
request.setAttribute("rows",rows); //
将包装好的ArrayList放到Request里以便jsp使用。

注意 ////之间的代码其实可作为公用代码,写到组件里去
(传入ResultSet做参数,返回包装好的ArrayList)

前台处理代码:假设这是一个单选框
<logic:iterate id="row" name="rows"> 
<html:radio property="roleId" value="id" idName="row"/> 
<bean:write name="row" property="roleDesc"/> 
</logic:iterate>

前台注释:
1 这里name="rows"就是后台setAttribute的名字 id="row"是给出循环里要引用每一行的标识
2 这里property="roleId"html表单的变量名 
value="id" 
是字段的名字
 
idName="row" 
就是第1行的id的值

3 这里name="row" 就是第1行的id的值 property="roleDesc"是字段名

如果是要显示这个resultset的记录,方法就跟 struts例子里的基本一样了:

<logic:iterate id="row" name="rows">
<tr>
<td>
<bean:write name="row" property="host"/>
</td>
<td>
<bean:write name="row" property="username"/>
</td>
<td>
<bean:write name="row" property="type"/>
</td>
<td>
<bean:write name="row" property="autoConnect"/>
</td>
</tr>
</logic:iterate>

这里的各项属性意义与上一样。

需要提醒的是:因为我们是将记录集放到request中的,所以这个<logic:iterate标签中不需要使用property属性,struts的例子是把这个记录集放到ActionForm中所以
在他的例子中<logic:iteratenameActionForm的名字,property是在ActionForm中定义的记录集(就是我们上面的rows)的名字了.

struts这样的表示方式还有一些另外的好处,例如可以用bean:write format属性
格式化字段的值,这是我们经常要用到的功能,象格式化日期和数字等。

通过这个例子大家可以做到举一反三的效果,凡是需要用到数据库中记录集的地方都可以依此类推,
想下拉表单,多选框等等。

 

 

抱歉!评论已关闭.