使用for循环在jsp中创建动态行

时间:2014-02-27 07:08:20

标签: java 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行,但根据编码功能,只有documentlist.size()=4时才会创建2行; 帮助我!

3 个答案:

答案 0 :(得分:1)

显然,当尺寸为4时,它只会产生2个拖曳, 当大小为6时,它将创建3行。如果你愿意,可以从循环中删除它 如果大小

,则创建等于数字的行

答案 1 :(得分:0)

从循环中删除if语句并正常创建行。

用这个改变你的循环 for(int arrayCounter = 0; arrayCounter&lt;(documentList.size()/ 2); arrayCounter ++)

并且对于最后一行,您可以使用if语句进行比较 if(documentList.size()/ 2)-1 == arrayCounter)..然后 你会得到你想要的东西

否则

for(int arrayCounter = 0; arrayCounter&lt; 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 ++

} }

答案 2 :(得分:0)

不要在jsp中使用scriptlet,Jsp是视图层,用作视图。有servlet / java-beans来放置你的所有java代码。

有jstl taglib,它有许多内置函数,使用它。你可以从here

获得它

在你的情况下循环列表就像这样:

  • 将jstl库添加到类路径

  • 首先在jsp顶部导入jstl taglib。

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

要在jsp中导入jstl,请执行以下操作:

<%@ 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代码。