尝试从java类向servlet发送ArrayList
。返回的ResultSet
值将传递给模型对象,并且此对象将添加到ArrayList
。但是,我需要在ArrayList
中检索此vieitems.jsp
。
DBController.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>
答案 0 :(得分:2)
在servlet代码中,使用指令request.setAttribute(&#34; itemList&#34;,avitems),将列表保存在请求对象中,并使用名称&#34; itemList&#34;引用它。
当您到达JSP时,从请求中检索列表是必要的,为此您只需要request.getAttribute(&#34; itemList&#34;)方法。
//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
}
%>
答案 1 :(得分:1)
在DbController.java中将该ArrayList声明设为静态
在DbController中创建一个方法
void static ArrayList<items> getList()
{
return avitems;
}
它将返回view.jsp
中的列表在view.jsp中导入DbController.java并添加此scriplet
<%
ArrayList<Item> list = DbController.getList(); //it will return the list
%>
迭代并在view.jsp中对此列表执行任何操作 我认为这会对你有帮助。