如何将ArrayList从Java类传递到jsp
问题描述:
试图从java类发送ArrayList
到servlet。将ResultSet
的返回值传递给模型对象,并将此对象添加到ArrayList
。不过,我需要在vieitems.jsp
中检索这个ArrayList
。如何将ArrayList从Java类传递到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>
答
在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
}
%>
答
作出这样的ArrayList声明静态在DbController.java
在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 这个列表我认为这会帮助你。
你知道关于['JSP'](http://beginnersbook.com/category/jsp-tutorial/)的任何内容吗? – 2014-09-22 23:10:25
[Pass from servlet to jsp variables](http://stackoverflow.com/questions/3608891/pass-variables-from-servlet-to-jsp) – 2014-09-22 23:16:37
@ PM77-1这里我试图通过一个从java类到jsp的arraylist,而不是从servlet到jsp。 – 2014-09-22 23:33:18