我有一个使用Hibernate的servlet,并从我的数据库中检索“Products”表。
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
tx= session.beginTransaction();
Query query=session.createQuery("from Products");
List mylist1=query.list();
tx.commit();
session.close();
HttpSession httpSession=request.getSession();
httpSession.setAttribute("Products", mylist1);
RequestDispatcher dispacther=request.getRequestDispatcher("index.jsp");
dispacther.forward(request, response);
我已将产品列表(pojo)转发给我的jsp。
我的问题是如何检索List的各个元素并使用我的jsp中的<jsp:useBean>
访问它们。
答案 0 :(得分:1)
你根本不需要<jsp:useBean>
这件事。您已经在使用servlet来管理模型。该模型已经通过EL表达式${Products}
在JSP中直接可用(尽管您最好将该事物重命名为products
,完全遵循标准的Java变量命名约定。)
httpSession.setAttribute("products", mylist1);
您可以通过使用括号表示法显式指定其索引来获取invididual元素:
${products[0]}
${products[1]}
${products[2]}
...
或者,更好的是,只需使用JSTL's <c:forEach>
<c:forEach items="${products}" var="product">
${product}
</c:forEach>
您的下一个问题可能是&#34;如何以表格格式打印每个产品的属性?&#34;。好吧,只需将<c:forEach>
放入HTML <table><tr><td>
并以${bean.propertyname}
格式引用属性即可。假设您的Product
包含id
,name
,description
和price
属性,请参阅以下内容:
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.id}</td>
<td><c:out value="${product.name}" /></td>
<td><c:out value="${product.description}" /></td>
<td><fmt:formatNumber value="${product.price}" type="currency" /></td>
</tr>
</c:forEach>
</table>