繁体   English   中英

如何将ArrayList从Java类传递给jsp

[英]How to pass an ArrayList from Java class to jsp

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

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

在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中对此列表执行任何操作,我认为这对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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