我对 JSTL 很陌生,很难准确掌握每个循环的工作原理。但是假设在我的 java bean 中我有一个非常简单的 while 循环,它遍历并获取对象的属性。当我记录它时,我从循环中得到了预期的输出。这只是一个看起来像 headerTest, headerMetaTest 的字符串。这是我的 java bean 的代码:
Iterator<Resource> serviceList = null;
serviceList = resource.getChild("header").listChildren();
while(serviceList.hasNext()){
Resource child = serviceList.next();
headerTitle = child.adaptTo(ValueMap.class).get("headerTitle", "");
headerMeta = child.adaptTo(ValueMap.class).get("headerMeta, "");
}
但是,当我尝试在 JSTL 中访问它时,我什么也没得到:
<c:forEach var="child" items="${serviceList}">
<p>${child.headerTitle}</p>
<p>${child.headerMeta}</p>
</c:forEach>
令人费解的是我没有收到任何错误,没有任何返回。有任何想法吗?真的,真的很迷茫,非常感谢任何帮助。我是这方面的新手,因此代码示例是我学习的好方法,如果可能的话那就太好了。
最佳答案
JSP 页面中有四个范围需要注意。
页面、请求、 session 和应用程序。
JSTL 标记通常会按该顺序查找属性。
页面映射到页面处理期间分配的属性,这些通常相当 罕见。
request是分配给ServletRequest的属性,它们是最常见的 属性在页面请求持续时间内持续使用,然后被丢弃。
例如
public void processMyServlet(ServletRequest request, ServletResponse){
...
request.setAttribute("myAttribute",attributeValue);
...
}
session 用于分配给 HttpSession 的属性。这对于 在用户 session 期间经常使用的用户值。
例如
public void processMyServlet(HttpServletRequest request, HttpServletResponse){
...
request.getSession().setAttribute("myAttribute",attributeValue);
...
}
application 用于分配给 ServletContext 的属性,这对于 值在整个应用程序中保持一致且不会更改。
例如
public void processMyServlet(HttpServletRequest request, HttpServletResponse){
...
request.getServletContext().setAttribute("myAttribute",attributeValue);
...
}
如果您正在调用一个调度 jsp 的 servlet,那么您至少需要。
request.setAttribute("serviceList",myResourceCollection);
servlet 处理过程中的某个地方。
如果你在 jsp 中完成所有操作,那么你将需要类似的东西
<% java code to create collection
request.setAttribute("serviceList",myResourceCollection);
%>
关于Java - 使用 JSTL 进行每个循环的基本操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17266124/