【问题标题】:How to pass an ArrayList from Java class to jsp如何将 ArrayList 从 Java 类传递给 jsp
【发布时间】:2014-11-17 00:38:00
【问题描述】:

试图将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> 

【问题讨论】:

  • 你知道JSP吗?
  • @PM77-1 在这里我试图将数组列表从 java 类传递给 jsp,而不是从 servlet 传递给 jsp。
  • 你的 POJO 是什么的一部分?另外,您可能想回答我的第一个问题。这不是夸夸其谈。
  • 我的第一条评论有一个 JSP 教程的链接。你可能想解决它。

标签: java jsp arraylist


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    在 DbController.java 中将 ArrayList 声明设为静态

    在 DbController 中创建一个方法

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

    它将返回 view.jsp 中的列表

    在 view.jsp 中导入 DbController.java 并添加这个脚本

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

    在 view.jsp 中对这个列表进行迭代并做任何你想做的事情 我想这会对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-02-01
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      • 2017-03-18
      • 2011-05-20
      • 2013-11-15
      • 2012-04-18
      • 1970-01-01
      相关资源
      最近更新 更多