我有一个任务,我应该使用 EJB、JPA、JSP 和其他一些东西(例如 CSS 和 javascript)制作一个简单的网站。
我正在尝试发送包含存储在我的数据库中的所有产品的列表。我首先在我的 servlet 中使用 ProductType 对象创建并填充一个列表,然后通过 RequestDispatcher 将其传递到我的 JSP。在我的 JSP 中,我使用 JSTL 遍历列表并打印产品名称。
但是什么也没有打印出来。我通过先前使用 JSTL choose 语句进行的测试知道该列表为空。 我还尝试在 servlet 中填充一个列表,然后在我的 servlet 上“打印”产品名称。当我在服务器上运行 servlet 时,会显示产品名称。这告诉我这不是我的数据库或我检索 ProductType 对象/元组的方式的问题,而是当我将列表从我的 servlet 传递到我的 JSP 时出了问题。
这是我的相关servlet代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
List<ProductType> productTypes = facade.getAllProducts();
// Set the list of product names as a request attribute
request.setAttribute("productTypeList", productTypes);
// Forward the request to the homePage.jsp page
RequestDispatcher dispatcher = request.getRequestDispatcher("homePage.jsp");
dispatcher.forward(request, response);
}
这是我的 homePage.jsp 文件中的相关代码
<p>
Our products
</p>
<%
List<ProductType> productList = (List<ProductType>)session.getAttribute("productTypeList");
request.setAttribute("productList", productList);
%>
<c:forEach items="${productTypeList}" var = "product">
<p><c:out value="${product.getProductName()}"/></p>
</c:forEach>
我想我也可以发布检索 ProductType 对象的代码
外观
@EJB
ProductTypeEAOLocal productTypeEAO;
public List<ProductType> getAllProducts() {
return productTypeEAO.getAllProductTypes();
}
产品类型EAOImpl
public List<ProductType> getAllProductTypes() {
return em.createQuery("SELECT p FROM ProductType p", ProductType.class).getResultList();
}
我不太确定自己做错了什么,总的来说,我对 EJB 和 Web 开发还很陌生。 从网上环顾四周,这似乎是解决问题的方法,老实说,我有点不知所措。非常感谢一些帮助。