在 JSP 中使用 for 循环 [英] Using for loop inside of a JSP
问题描述
我想遍历Festivals"的 ArrayList 并使用 get 方法获取它们的信息,打印出它的所有值.出于某种原因,当我使用这段代码时,它总是会选择第0"个值而不是增加循环.
I want to loop through an ArrayList of "Festivals" and get their information with get methods, printing out all its values. For some reason when I use this code, it will always choose the "0"th value and not increment the loop.
如果我将值硬编码为get(1)",它会得到正确的值,所以我的问题很明显是语法问题.
If I hard code the values as "get(1)" it will get the correct values so my issue is clearly with the syntax.
<h1>All Festival Information</h1>
<jsp:useBean id="allFestivals" type="java.util.ArrayList" scope="session" />
<table border="1">
<tr>
<td>Festival Name:</td>
<td>Location:</td>
<td>Start Date:</td>
<td>End Date:</td>
<td>URL:</td>
</tr>
<% for(int i = 0; i < allFestivals.size(); i+=1) { %>
<tr>
<td>${allFestivals.get(i).getFestivalName()}</td>
<td>${allFestivals.get(i).getLocation()}</td>
<td>${allFestivals.get(i).getStartDate()}</td>
<td>${allFestivals.get(i).getEndDate()}</td>
<td>${allFestivals.get(i).getURL()}</td>
</tr>
<% } %>
</table>
推荐答案
你的具体问题是因为你混合了 气馁和老派 scriptlets <% %>
及其后继EL ${}
.它们不共享相同的变量作用域.allFestivals
在 scriptlet 范围内不可用,i
在 EL 范围内不可用.
You concrete problem is caused because you're mixing discouraged and old school scriptlets <% %>
with its successor EL ${}
. They do not share the same variable scope. The allFestivals
is not available in scriptlet scope and the i
is not available in EL scope.
您应该安装 JSTL(<-- 单击链接获取说明)并在 JSP 顶部将其声明为如下:
You should install JSTL (<-- click the link for instructions) and declare it in top of JSP as follows:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
然后按如下方式遍历列表:
and then iterate over the list as follows:
<c:forEach items="${allFestivals}" var="festival">
<tr>
<td>${festival.festivalName}</td>
<td>${festival.location}</td>
<td>${festival.startDate}</td>
<td>${festival.endDate}</td>
<td>${festival.URL}</td>
</tr>
</c:forEach>
(注意可能的XSS 攻击漏洞,使用<c:out>
相应)
(beware of possible XSS attack holes, use <c:out>
accordingly)
不要忘记删除 <jsp:useBean>
因为当您使用 servlet 作为模型和视图时,它在这里没有任何价值控制器.这只会导致混乱.另请参阅我们的 servlet wiki 页面.此外,您可以通过 web.xml
中的以下条目禁用 scriptlets,这样您就不会意外使用它们:
Don't forget to remove the <jsp:useBean>
as it has no utter value here when you're using a servlet as model-and-view controller. It would only lead to confusion. See also our servlets wiki page. Further you would do yourself a favour to disable scriptlets by the following entry in web.xml
so that you won't accidently use them:
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</jsp-config>
这篇关于在 JSP 中使用 for 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!