想要使用servlet从数据库中检索数据并在jsp中显示它

时间:2016-04-12 17:28:19

标签: database servlets

我想使用servlet从数据库中检索数据并将其显示到jsp文件中,但检索到的只是表的第一行。我想要检索所有行。有人可以帮助我吗?谢谢,这是我的代码:

的Servlet

    arr.sort(function (x, y) {
        return x < y;
    })

JSP:

    try{

        DBConnection connection = new DBConnection();
        Connection con = connection.Connect();
        ResultSet rs;
        Statement st = con.createStatement();
        java.sql.PreparedStatement ps=con.prepareStatement("SELECT Nume,Descriere,Ingrediente,Mod_preparare,Imagini,Total_grasimi,Total_carbohidrati,Total_proteine,Total_calorii FROM reteta");
        rs=ps.executeQuery();

        while(rs.next()){
            //name
            String Nume = rs.getString("Nume");
            request.setAttribute("Nume",Nume);

            //descripton
            String Descriere = rs.getString("Descriere");
            request.setAttribute("Descriere",Descriere);

            //images
            String Imagini = rs.getString("Imagini");
            request.setAttribute("Imagini",Imagini);


       request.getRequestDispatcher("/retete.jsp").forward(request, response);


        }

    rs.close();
    st.close();
    con.close();
    }
    catch (Exception e2)
    {
      e2.printStackTrace();
    }

    finally
    {
      out.close();
    }
}

1 个答案:

答案 0 :(得分:0)

您正在设置属性并在while循环中转发请求:这可能是您没有得到预期结果的原因

你应该使用每个字段来创建一个对象,每次循环都将新创建的对象存储在一个集合中(数组,arraylist,linkedlist map ......选择权属于你),然后在循环外创建一个属性, value是用while循环中创建的对象填充的集合,最后将请求转发给Jsp

// create a new collection be it an array, arrayList, linkedList....
YourCollection yc = new YourCollection();

while(rs.next()){
        //name
        String Nume = rs.getString("Nume");
        //descripton
        String Descriere = rs.getString("Descriere");
        //images
        String Imagini = rs.getString("Imagini");

        // create object with db data;
        YourClass yourObject = new YourClass(Nume, Descriere, Imagini);
        // add object to collection
        YourCollection.add(yourObject);
}
// create attribute from collection
request.setAttribute("YourCollection", yc);

request.getRequestDispatcher("/retete.jsp").forward(request,response);

在Jsp中,您将能够轻松访问该属性并使用foreach JSTL标记(例如)循环遍历该集合,并通过表达式语言遍历每个对象的实例变量(我在示例中使用了点符号)< / p>

<c:foreach var="yourVarName" items="${YourCollection}">

            <a href="images/{yourVarName.imagini} " class="gall_item"><img src="images/${yourVarName.imagini}" alt=""></a>
            <div class="gall_bot">
            <div class="text1"><a href="#">${yourVarName.nume} </a></div>
    ${yourVarName.descriere} 
            <br>
            <button type = "submit" class = "btn" >more</button>
             <!-- check closing divs.... -->
            </div>
          </div>
        </div>
      </div>

</c:foreach>

注意:通过点表示法访问的属性对应于每个对象的实例变量,不需要按照javabean规范进行大写。