所以我有这个类(我从中删除了一些方法来最小化你的工作):
public class ContextListener implements ServletContextListener {
ArrayList<Product> products = new ArrayList();
ServletContext context ;
@Override
public void contextInitialized(ServletContextEvent sce) {
try {
this.getProductsFromDB(); // this method puts the products in the arraylist
} catch (SQLException ex) {
Logger.getLogger(ContextListener.class.getName()).log(Level.SEVERE, null, ex);
}
context = sce.getServletContext();
context.setAttribute("products", products);
}
我想在这样的 JSP 页面中获取ArrayList
:
<%! ArrayList<Product> products = (ArrayList<Product>)getServletContext().getAttribute("products"); %>
但实际上它不起作用。
您需要将其分配给完全限定的名称。
<%
java.util.ArrayList<Product> products = (java.util.ArrayList<you.package.for.Product>) getServletContext().getAttribute("products");
pageContext.setAttribute("products", products);
%>
接下来,您应该能够通过其属性名称调用它:
${products}
像这样使用 JSTL
${applicationScope['products']}
或仅属性名称
${products}
注意:不建议使用脚本。
您必须使用 JSTL 中的c:forEach
标记迭代列表
<c:forEach items="${products}" var="product">
<li><c:out value="${product.field}"/></li>
</c:forEach>
其中field
表示Product
Java Bean 中的属性