Servlet:使用HttpSession,array存储/打印特定属性的问题

时间:2015-11-12 14:59:16

标签: java arrays servlets jdbc httpsession

我仍然是servlets和JDBC的新手,并希望对以下代码有所帮助:

try{
        String selectSQL = "select * from product_list where category = '"+category+"'";
        Statement stmt = conn.createStatement();
        ResultSet rs1 = stmt.executeQuery(selectSQL);

        ArrayList<Float> idList = new ArrayList<Float>();

out.println("<table border=\"1\"><tr><th>Item_ID</th><th>Item_name</th><th>Title</th><th>Category</th><th>Image_name</th><th>Price</th><th>Stock_Count</th></tr>");

while(rs1.next()){

    out.println("<tr><td>"+ rs1.getFloat("item_id") + "</td>");
    out.println("<td>" + rs1.getString("item_name") + "</td>"); 
    out.println("<td>"+"<a href =\"ItemDetail\">" + rs1.getString("title")+"</a>" + "</td>");
    out.println("<td>" + rs1.getString("category") + "</td>");
    out.println("<td>" + rs1.getString("image_name") + "</td>");
    out.println("<td> " + rs1.getFloat("price") + "</td>");
    out.println("<td> " + rs1.getFloat("stock_count") + "</td>");
    out.println("</tr>");
         HttpSession session = request.getSession(true);
        idList.add(rs1.getFloat("recording_id"));
        session.setAttribute("id", idList);
}
out.println("</table>");

        conn.close();
    } catch(SQLException se) {
        System.err.println(se);
    }

我想要做的是它会在会话中存储每一个item_id,但只显示另一个servlet中用户点击其标题链接的那个(每个标题都有相同的超链接)的详细信息,我有试图将所有id存储在一个数组列表中,但是没有任何东西显示在另一个意图接收到数组列表的servlet上,那里我做错了什么,任何帮助都会受到赞赏。

以下是在不同的servlet中用于从上表

接收属性的代码
HttpSession session = request.getSession(true);
    ArrayList<Float> id = (ArrayList<Float>) session.getAttribute("id");

2 个答案:

答案 0 :(得分:0)

这是一个有效的示例代码。相应地修改

 //My first servlet using Java-8
 try (Connection con = DriverManager.getConnection("xxxx")) {
        String category = "fish";
        try (PrintWriter out = response.getWriter()) {
            try (ResultSet rs1 = con.createStatement()
                    .executeQuery("select * from product_list where category = '" + category + "'")) {
                HttpSession session = request.getSession();
                ArrayList<Float> list = new ArrayList<>();
                out.print(
                        "<table border=\"1\"><tr><th>Item_ID</th><th>Item_name</th><th>Title</th><th>Category</th><th>Image_name</th><th>Price</th><th>Stock_Count</th></tr>");
                while (rs1.next()) {
                    list.add(rs1.getFloat("item_id"));
                    out.println("<tr><td>" + rs1.getFloat("item_id") + "</td>");
                    out.println("<td>" + rs1.getString("item_name") + "</td>");
                    out.println("<td>" + "<a href ='" + request.getContextPath() + "/Second?id="+rs1.getFloat("item_id")+"'>"
                            + rs1.getString("title") + "</a>" + "</td>");
                    out.println("<td>" + rs1.getString("category") + "</td>");
                    out.println("<td>" + rs1.getString("image_name") + "</td>");
                    out.println("<td> " + rs1.getFloat("price") + "</td>");
                    out.println("<td> " + rs1.getFloat("stock_count") + "</td>");
                    out.println("</tr>");
                }
                session.setAttribute("list", list);
                out.println("</table>");
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

我的第二个servlet在这里

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // then just use that to get it through a GET Http Method
    String id = request.getParameter("id");
    HttpSession session = request.getSession();
    ArrayList<Float> list = (ArrayList<Float>) session.getAttribute("list");
    response.getWriter().append("item:  ").append(String.valueOf(list.get(0)));
}

在屏幕上打印输出项目:45.0

希望它有所帮助。

答案 1 :(得分:0)

杰夫,杰夫,杰夫......

我认为你的问题的答案很简单,但我想帮你清理一下,因为这里有很多可以做得更好的事情。这段代码有资源泄漏,可以教你一些坏习惯。

ID没有正确显示的原因可能是这一行:

    HttpSession session = request.getSession(true);
    idList.add(rs1.getFloat("recording_id"));
    session.setAttribute("id", idList);
} //End while

每次迭代ResultSet时都会重置idList属性。您需要在循环之外获取会话,修改ArrayList,然后将属性设置一次。

HttpSession session = request.getSession(true); //Get the session only once
ArrayList<Float> idList = new ArrayList<Float>();   //Declare output variables outside of the try block.

//Now declare your JDBC resources; always declare them as null outside of the try block.
//This allows you to close them properly later.

PreparedStatement stmt = null;
ResultSet rs1 = null;

try{
    String selectSQL = "select * from product_list where category = ?";

    stmt = conn.prepareStatement(selectSQL);

    stmt.setString(1, category);

    rs1 = stmt.executeQuery(selectSQL);

    out.println("<table border=\"1\"><tr><th>Item_ID</th><th>Item_name</th><th>Title</th><th>Category</th><th>Image_name</th><th>Price</th><th>Stock_Count</th></tr>");

    while(rs1.next()){

         out.println("<tr><td>"+ rs1.getFloat("item_id") + "</td>");
         out.println("<td>" + rs1.getString("item_name") + "</td>"); 
         out.println("<td>"+"<a href =\"ItemDetail\">" + rs1.getString("title")+"</a>" + "</td>");
         out.println("<td>" + rs1.getString("category") + "</td>");
         out.println("<td>" + rs1.getString("image_name") + "</td>");
         out.println("<td> " + rs1.getFloat("price") + "</td>");
         out.println("<td> " + rs1.getFloat("stock_count") + "</td>");
         out.println("</tr>");
         idList.add(rs1.getFloat("recording_id")); //Add to the list in the loop.

       }

    out.println("</table>");

    } catch(SQLException se) {
        System.err.println(se); //This is OK, but consider 'throw new RuntimeException(se)' here instead so that the exception propagates.
    } finally {
   //Close the resources backwards from the way that they were opened.
   //Check them all for null first in case there's an error in the middle somewhere, 
   //otherwise you'll get a NullPointerException from the finally block and it will "swallow"
   //the original error.
   if(rs1 != null) {
      try {
        rs1.close();
      } catch(SQLException x) {
        System.err.println(x); //Don't throw here; keep trying to close resources
      }
   }

   if(stmt != null) {
      try {
        stmt.close();
      } catch(SQLException x) {
        System.err.println(x); 
      }
   }

   if(conn != null) {
      try {
        stmt.close();
      } catch(SQLException x) {
        System.err.println(x);
      }
   }
}

session.setAttribute("id", idList); //Set the list once and only once.