Jsp 如何从contextListener获取属性?

Jsp 如何从contextListener获取属性?,jsp,servlets,web,Jsp,Servlets,Web,因此,我有一个类(我从中删除了一些方法以最小化您的工作): 但实际上它不起作用。像这样使用JSTL ${applicationScope['products']} 或者只是属性名 ${products} 注意:Scriptlet是不推荐的 您必须在JSTL中使用c:forEach标记来迭代列表 <c:forEach items="${products}" var="product"> <li><c:out value="${product.field}"/&

因此,我有一个类(我从中删除了一些方法以最小化您的工作):

但实际上它不起作用。

像这样使用JSTL

${applicationScope['products']}
或者只是属性名

${products}
注意:Scriptlet是不推荐的

您必须在JSTL中使用
c:forEach
标记来迭代列表

<c:forEach items="${products}" var="product">
  <li><c:out value="${product.field}"/></li>
 </c:forEach>


  • 其中,
    字段
    表示
    产品
    JavaBean中的属性

    您需要将其分配给完全限定名

    <%
       java.util.ArrayList<Product> products = (java.util.ArrayList<you.package.for.Product>) getServletContext().getAttribute("products");
       pageContext.setAttribute("products", products);
    %>
    

    您的侦听器是否已在
    web.xml
    中注册?是的。我在一个servlet中得到了这个属性,它工作了。在jsp页面中没有,但如何将其分配给ArrayList?您已经将该列表分配给了应用程序范围属性
    products
    。您可以使用JSTLi在jsp中检索列表。我对jst是新手,我刚刚开始,它对我不起作用。可以添加检索列表的代码吗?可以添加
    getProductsFromDB
    方法的代码吗?我想确保您实际上是在iti am中设置数据,因为我可以通过request.getSession().getServletContext().getAttribute(“产品”)在servlet中读取数据;但是我不知道在jsp中,我不知道把${products}放在哪里,因为我需要foreach在这个数组中,您没有完全提供您想要实现的内容-我修复了您编写的scriptlet:)代码被重写了,所以您应该能够在jsp中使用scriptlet中的数据
    <c:forEach items="${products}" var="product">
      <li><c:out value="${product.field}"/></li>
     </c:forEach>
    
    <%
       java.util.ArrayList<Product> products = (java.util.ArrayList<you.package.for.Product>) getServletContext().getAttribute("products");
       pageContext.setAttribute("products", products);
    %>
    
    ${products}