简体   繁体   中英

How to pass an ArrayList from Java class to jsp

Attempting to send an ArrayList from java class to servlet. The returned values of ResultSet is passed on to a model object and this object is added to an ArrayList . However I need retrieve this ArrayList in 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> 

In the servlet code, with the instruction request.setAttribute("itemList", avitems), you save your list in the request object, and use the name "itemList" for refering it.

When you arrive to your JSP, it's necessary to retrieve the list from the request, and for that you just need the request.getAttribute("itemList") method.

   //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
}
%>

Make that ArrayList declaration static in DbController.java

In DbController create one method

    void static ArrayList<items> getList()
     {
            return avitems;
          }

it will return you the list in view.jsp

in view.jsp import DbController.java and add this scriplet

       <%
              ArrayList<Item> list = DbController.getList(); //it will return the list
       %>

iterate and do whatever you want to do with this list in your view.jsp i think this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM