示例:使用 tsx:repeat JavaServer Pages 标记在结果集上迭代(不推荐使用)
<tsx:repeat> 标记迭代结果集。此结果集包含在 Bean 中。此 Bean 可以是静态的 Bean(例如,使用 IBM® WebSphere® Studio 数据库向导创建的 Bean)或动态生成的 Bean(例如,由 <tsx:dbquery> 语法生成的 Bean)。

下表是一个名为 myBean 的 Bean 的内容的图形表示法:
列 | col1 | col2 | col3 |
---|---|---|---|
row0 | friends | Romans | countrymen |
row1 | bacon | lettuce | tomato |
row2 | May | June | July |
若仔细观察此 Bean,您可注意到:
- 数据库表中的列名成为该 Bean 的属性名。<tsx:dbquery> 部分描述将列名映射到不同属性名的技术。
- 该 Bean 属性已建立索引。例如,myBean.get(Col1(row2)) 返回 May。
- 查询结果用行显示。<tsx:repeat> 标记从起始行开始逐行迭代。
下表比较了使用 <tsx:repeat> 标记在静态 Bean 和动态生成的 Bean 上进行迭代的异同:
静态 Bean 示例 | <tsx:repeat> Bean 示例 |
---|---|
myBean.class // Code to get a connection // Code to get the data Select * from myTable; // Code to close the connectionJSP 文件 <tsx:repeat index=abc> <tsx:getProperty name="myBean" property="col1(abc)" /> </tsx:repeat> 注:
|
JSP 文件<tsx:dbconnect id="conn" userid="alice"passwd="test" url="jdbc:db2:sample" driver="COM.ibm.db2.jdbc.app.DB2Driver"> </tsx:dbconnect> <tsx:dbquery id="dynamic" connection="conn" > Select * from myTable; </tsx:dbquery> <tsx:repeat index=abc> <tsx:getProperty name="dynamic" property="col1(abc)" /> </tsx:repeat> 注:
|
隐式和显式索引
示例 1、2 和 3 显示如何使用 <tsx:repeat> 标记。如果所有索引的属性的元素不超过 300 个,那么这些示例将产生相同的输出。如果多于 300 个元素,那么示例 1 和 2 显示将所有元素,而示例 3 仅显示前 300 个元素。
示例 1 显示隐式索引,其开始和结束索引均使用缺省值。使用最小索引属性数的 Bean 限制循环重复的次数。
<table> <tsx:repeat> <tr><td><tsx:getProperty name="serviceLocationsQuery" property="city" /> </tr></td> <tr><td><tsx:getProperty name="serviceLocationsQuery" property="address" /> </tr></td> <tr><td><tsx:getProperty name="serviceLocationsQuery" property="telephone" /> </tr></td> </tsx:repeat> </table>
示例 2 显示索引、开始索引和结束索引:
<table> <tsx:repeat index=myIndex start=0 end=2147483647> <tr><td><tsx:getProperty name="serviceLocationsQuery" property=city(myIndex) /> </tr></td> <tr><td><tsx:getProperty name="serviceLocationsQuery" property=address(myIndex) /> </tr></td> <tr><td><tsx:getProperty name="serviceLocationsQuery" property=telephone(myIndex) /> </tr></td> </tsx:repeat> </table>
示例 3 显示显式索引,其开始索引和结束索引均为隐式索引。尽管指定了 index 属性,您仍可对已索引的属性 city 进行隐式索引,因为不需要 (myIndex) 标记。
<table> <tsx:repeat index=myIndex end=299> <tr><td><tsx:getProperty name="serviceLocationsQuery" property="city" /t> </tr></td> <tr><td><tsx:getProperty name="serviceLocationsQuery" property="address(myIndex)" /> </tr></td> <tr><td><tsx:getProperty name="serviceLocationsQuery" property="telephone(myIndex)" /> </tr></td> </tsx:repeat> </table>
嵌套 <tsx:repeat> 块
您可以嵌套 <tsx:repeat> 块。每个块可以分别进行索引。此能力对交错两个 Bean 上的属性或具有子属性的属性有用。在此示例中,嵌套两个 <tsx:repeat> 块,以显示用户购物车中每张光盘上的歌目。
<tsx:repeat index=cdindex> <h1><tsx:getProperty name="shoppingCart" property=cds.title /></h1> <table> <tsx:repeat> <tr><td><tsx:getProperty name="shoppingCart" property=cds(cdindex).playlist /> </td></tr> </tsx:repeat> </table> </tsx:repeat>