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

Java 使用for循环在jsp中创建动态行,java,jsp,Java,Jsp,我想用这种方法创建一个具有动态行数的表 <table width="89%" style="margin-left:30px;"> <% for (int arrayCounter = 0; arrayCounter < documentList.size(); arrayCounter++) { %> <% int test = arrayCounter; if((arrayCo

我想用这种方法创建一个具有动态行数的表

<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行;

救救我

显然,当尺寸为4时,只会产生2个拖缆, 当大小为6时,将创建3行。如果需要,请从循环中删除it语句
创建等于number if size的行

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

用这个改变你的循环 对于(int-arrayCounter=0;arrayCounter<(documentList.size()/2);arrayCounter++)

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

否则

对于(int-arrayCounter=0;arrayCounter }
}不要在jsp中使用scriptlet,jsp是视图层,用作视图。有servlet/JavaBean来放置所有java代码

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

在您的情况下,要循环列表,请执行以下操作:

  • 将jstl库添加到类路径

  • 首先在jsp顶部导入jstl标记库

  • 然后在jsp中使用jstl标记

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

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
如果要为每个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>

//这里,如果您想要循环索引,您可以得到:${loop.index}
//如果要显示doc的某些属性,请执行以下操作:${doc.someProperty},
jstl将调用someProperty的getter方法来获取值。

阅读更多有关如何避免jsp中的java代码的信息。

您认为它可以解决我们的问题吗?因为您的循环按大小运行了/2次,但我们需要迭代所有数据?
<c:forEach items="${documentList}" var="doc">
   //here you can access one element by doc like: ${doc}
</c:forEach>
<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>