2014-09-22 50 views
1

試圖從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> 
+2

你知道關於['JSP'](http://beginnersbook.com/category/jsp-tutorial/)的任何內容嗎? – 2014-09-22 23:10:25

+0

[Pass from servlet to jsp variables](http://stackoverflow.com/questions/3608891/pass-variables-from-servlet-to-jsp) – 2014-09-22 23:16:37

+0

@ PM77-1這裏我試圖通過一個從java類到jsp的arraylist,而不是從servlet到jsp。 – 2014-09-22 23:33:18

回答

2

在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 
} 
%> 
1

作出這樣的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 這個列表我認爲這會幫助你。

相關問題