使用 for 循环在 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 行;帮帮我!

显然,

当大小为 2 时,它只会产生 4 个拖曳,当大小为 6 时,它将创建 3 行。如果需要,请从循环中删除它语句创建等于数字的行 if size

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

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

对于最后一行,您可以有 if 语句,它将比较if (documentList.size()/2)-1 == arrayCounter)..然后你会得到你想要的

for (int arrayCounter

= 0; arrayCounter

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

}}

不要在 jsp 中使用脚本,Jsp 是视图层,用作视图。 有servlet/java-beans可以放置所有Java代码。

有jstl taglib,它有很多内置函数,使用它。 你可以从这里得到它

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

  • 将 jstl 库添加到类路径

  • 首先在 jsp 的顶部导入 jstl 标签库。

  • 然后,您就有了要在 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>

在此处阅读更多内容,了解如何避免在 JSP 中使用 Java 代码。

最新更新