【问题标题】:Java - Basic for each loop with JSTLJava - 使用 JSTL 的每个循环的基础
【发布时间】:2013-06-23 23:05:47
【问题描述】:

我是 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>

令人费解的部分是我没有收到任何错误,没有任何东西只是返回。有任何想法吗?真的,真的迷失了这个,非常感谢任何帮助。我是这方面的新手,所以代码示例是我学习的好方法,如果可能的话会很棒。

【问题讨论】:

  • 您是否将 serviceList 添加到页面上下文中?
  • 我将其设置为资源您是指将其设置在 JSTL 的 pageContext 中吗?如果是这样的话,我不完全确定你会怎么做。
  • jsp页面不知道${serviceList}是什么,所以它什么都不输出。

标签: java jstl


【解决方案1】:

在 JSP 页面中需要注意四个范围。

页面、请求、会话和应用程序。

JSTL 标记通常会按该顺序查找属性。

页面映射到页面处理过程中分配的属性,这些通常是相当的 很少见。

request 用于分配给 ServletRequest 的属性,它们是最常见的 在页面请求期间持续使用的属性,然后被丢弃。

例如

public void processMyServlet(ServletRequest request, ServletResponse){
    ...
    request.setAttribute("myAttribute",attributeValue);
    ...
}

session 用于分配给 HttpSession 的属性。这对 在用户会话期间经常使用的用户值。

例如

public void processMyServlet(HttpServletRequest request, HttpServletResponse){
    ...
    request.getSession().setAttribute("myAttribute",attributeValue);
    ...
}

应用程序用于分配给 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); 
%>

【讨论】:

    猜你喜欢
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 2015-08-13
    相关资源
    最近更新 更多