嗨,我想在 scriplet i 中使用 jSTL 变量,当 num==3 时,我想打印一个“hello”,它尝试获取以下代码,但 i 的值仍然为零。
我想获取num
的值并将其增加1,然后检查num==3
是否,然后在条件为真时打印hello,再次将值重新分配为零。
<c:set var="num" value="0"></c:set>
<c:forEach items="${requestScope.Products}" var="emp" begin="0" end="${size}" >
<c:if test="${num==3}">
<h1>hello</h1>
</c:if>
<%! int var=0;%>
<% var=Integer.parseInt(pageContext.getAttribute("num").toString());%>
<%
System.out.println(var);
var=var+1;%>
<h2><c:out value="${num}"></c:out></h2>
<td width="100">
<img src="images/${emp.image}" width="100" height="100"/>
Title<p>${emp.title}</p>
Price<p>${emp.price}</p>
<input type="submit" value="Buy No" class="bluebutton"/>
</c:forEach>
<小时/>
编辑
我想在一行中显示最多 3 条记录,就像如果我有 15 条记录那么就会有 5 行。当我这样写时,行中会有 3 列问题
<tr> <td>${tile}</td> <td>price<td>
在 for 循环中,它显示第一条记录 3 次,但我希望每列都有新记录。
这是我修改后的代码:
<% int size=Integer.parseInt(request.getAttribute("size").toString());
%>
<h1><%= size%></h1>
<table border="1" width="50%">
<tr >
<c:set var="num" value="0"></c:set>
<c:forEach items="${requestScope.Products}" var="emp" begin="0" end="${size}" varStatus="loop">
<c:choose>
<c:when test="${num==3}">
<tr>
</tr>
<c:set var="num" value="0"></c:set>
</c:when>
<c:otherwise>
<td width="100">
<img src="images/${emp.image}" width="100" height="100"/>
Title<p>${emp.title}</p>
Price<p>${emp.price}</p>
<input type="submit" value="Buy No" class="bluebutton"/>
</td>
</c:otherwise>
</c:choose>
<c:set var="num" value="${num + 1}" />
<h2><c:out value="${num}"></c:out></h2>
</c:forEach>
</tr>
</table>
最佳答案
我想获取 num 的值并将其增加 1,然后检查 num==3 是否,然后在条件为 true 时打印 hello,再次将值重新设置为零
阅读内联评论以获取更多信息。
示例代码:(根据您的要求修改)
<c:set var="num" value="0"></c:set> <!-- initial value -->
<c:forEach items="${requestScope.Products}" var="emp">
<c:if test="${num==3}">
<h1>hello</h1>
<c:set var="num" value="0"></c:set> <!-- re-initialize value -->
</c:if>
<c:set var="num" value="${num + 1}" /> <!-- increment value -->
<h2>
<c:out value="${num}"></c:out>
</h2>
</c:forEach>
<小时/>
编辑
我想在一行中显示最多 3 条记录,就像如果我有 15 条记录那么就会有 5 行。在行中将有 3 列。
<c:set var="Products" value="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15" scope="request"/>
<c:set var="beginTR" value="true" /> <!-- to check for tr start -->
<table border="1">
<c:forEach items="${requestScope.Products}" var="emp"
varStatus="status">
<c:if test="${status.index%3==0}"> <!-- check for columns no -->
<c:if test="${beginTR}">
<tr>
<c:set var="beginTR" value="false" />
</c:if>
<c:if test="${!beginTR}">
</tr>
<c:set var="beginTR" value="true" />
</c:if>
</c:if>
<td>
<c:out value="${emp}"></c:out> <!-- Fit your actual code here -->
</td>
</c:forEach>
</table>
截图:
关于java - 在 Scriptlet 中访问 JSTL 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23722359/