gpt4 book ai didi

java - 如何将 ArrayList 从 Java 类传递给 jsp

转载 作者:行者123 更新时间:2023-11-29 05:17:36 25 4
gpt4 key购买 nike

试图将 ArrayList 从 java 类发送到 servlet。 ResultSet 的返回值被传递给一个模型对象,该对象被添加到一个ArrayList。但是,我需要在 vieitems.jsp 中检索此 ArrayList

数据库 Controller .java

 public void getAvailableItems(String sqlst) throws Exception {
Connection connection = getConnection();
Statement stm = connection.createStatement();
ResultSet rst = stm.executeQuery(sqlst);

ArrayList<Item> avitems = new ArrayList<Item>();
while (rst.next()) {
String itemname = rst.getString("ItemName");
String description = rst.getString("Description");
int qtyonhand = rst.getInt("QtyOnHand");
int reorderlevel = rst.getInt("ReorderLevel");
double unitprice = rst.getDouble("unitprice");
Item item = new Item(itemname, description, qtyonhand, reorderlevel, unitprice);
avitems.add(item);
}
//i need to send avitems to ViewItems.jsp
}

ViewItems.jsp

 <form>
<Table border="1">
<tbody>
<tr> <td>Item Code</td><td>Item Name</td><td>Description</td><td> Qty On Hand</td><td>Reorder Level</td></tr>
//here i need to set the values of arraylist avitems
</tbody>
</Table>
</form>

最佳答案

在 servlet 代码中,使用指令 request.setAttribute("itemList", avitems),您将列表保存在请求对象中,并使用名称“itemList”来引用它。

当您到达 JSP 时,有必要从请求中检索列表,为此您只需要 request.getAttribute("itemList") 方法。

   //Servlet page code DBController.java
request.setAttribute("itemList", avitems);
ServletContext context= getServletContext();
RequestDispatcher rd= context.getRequestDispatcher("/ViewItems.jsp");
rd.forward(request, response);


// Jsp Page code ViewItems.jsp
<%
// retrieve your list from the request, with casting
ArrayList<Item> list = (ArrayList<Item>) request.getAttribute("itemList");

// print the information about every category of the list
for(Item item : list)
{
// do your work
}
%>

关于java - 如何将 ArrayList 从 Java 类传递给 jsp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25984367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com