2014-02-27 48 views
0

创建JSP动态记录,我想通过这种方式使用循环

<table width="89%" style="margin-left:30px;">     <% 
    for (int arrayCounter = 0; arrayCounter < documentList.size(); arrayCounter++) { 

    %> 
    <% 
    int test = arrayCounter; 
    if((arrayCounter%2)==0)){      
    %> 
    <tr> 
    <% 
    } %> 
    <td style="width:2%"> 

    </td> 
    <td style="width:20%;align:left;"> 
    </td> 

     <td style="width:30%;align:left;"> 

    </td> 
    <% 
    if((arrayCounter%2)==0){ 
     %> 
    </tr> 
    <% } %> 

    <% 
    } 
    %> 
    </table> 
在我的jsp这种方式,将创建4行

创建一个表具有动态无行,但根据编码功能,将创建2只有行documentlist.size()=4; 帮帮我!

+0

看到我的回答低于 – Rembo

回答

1

很明显,当尺寸为4时,它只会创建2个拖拽,当尺寸为6时,它会创建3个行, 。如果你想 创建行数等于

0

删除if语句从循环,并创建行正常。 (; arrayCounter <(documentList.size()/ 2); INT arrayCounter = 0 arrayCounter ++)

与此 为改变你的循环

和最后一排,你可以有if语句将比较,如果 ( documentList.size()/ 2)-1 == arrayCounter)..然后 你会得到你在找什么

其他

为(INT arrayCounter = 0; arrayCounter < documentList.size(); arrayCounter ++){

if (documentList.size()/2)-1 == arrayCounter){ create 1 row}else{ 
create 1st row and then arraycounter ++ 
create 2nd row and then arraycounter ++ 

} }

+0

你是否会解决我们的问题bcoz你的循环按大小运行/ 2次,但我们需要迭代所有数据? –

0

不要在JSP使用小脚本,JSP是是视图层,用作图。有servlet/java-beans将你所有的java代码。

有jstl taglib,它有许多inbuild功能,使用它。你可以从here

得到它在你的情况下,遍历一个列表这样做:

  • 添加JSTL库到类路径在JSP的顶部

  • 首次进口JSTL标签库。

  • 然后你有jstl标签在你的jsp中使用。

要导入JSTL在JSP中不喜欢:

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

的循环在JSTL一个List,有c:forEach标签,你可以用它喜欢:

<c:forEach items="${documentList}" var="doc"> 
    //here you can access one element by doc like: ${doc} 
</c:forEach> 

如果你想为每个documentList元素生成表格行,然后像这样做:

<table width="89%" style="margin-left:30px;"> 
<c:forEach items="${documentList}" var="doc" varStatus="loop"> 
    <tr> 
    <td style="width:2%"> 
     //here if you want loop index you can get like: ${loop.index} 
    </td> 
    <td style="width:20%;align:left;"> 
    //if you want to display some property of doc then do like: ${doc.someProperty}, 
     jstl will call getter method of someProperty to get the value. 

    </td> 
    <td style="width:30%;align:left;"> 

    </td> 
    </tr> 
</c:forEach> 
</table> 

阅读全文here如何避免jsp中的java代码。