2014-02-27 84 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代碼。