Jsp如何使用jstl显示hashmap中的对象成员值

时间:2014-04-18 03:02:51

标签: jsp jstl

我将hashmap从servlet传递给jsp,并使用jstl在jsp中循环遍历hashmap。我在hashmap中传递了朋友类对象列表。

这是我的代码。

 HashMap<Integer, jmsg.friends> myfriends = new HashMap<Integer, jmsg.friends>();
     ResultSet frnddata;
     int c = 0;

     request.setAttribute("friendslist",myfrnd);

     for (int i=0; i<myfrnd.size(); i++) {

     frnddata = statement.executeQuery("SELECT * FROM signup WHERE username = '"+ myfrnd.get(i) +"' ");     

      while(frnddata.next()){

          jmsg.friends f = new jmsg.friends();
          f.fullname = frnddata.getString("name");
          f.country = frnddata.getString("country");
          f.city = frnddata.getString("city");
          f.gender = frnddata.getString("gender");

          myfriends.put(c,f);

          c = c  + 1;
          out.println(c);

      }
      frnddata = null;

      }

    request.setAttribute("friends",myfriends); 

    ServletContext sc = this.getServletContext();
    RequestDispatcher rd = sc.getRequestDispatcher("/dashboard.jsp");
    rd.forward(request, response);

在Jsp中

  <c:forEach items="${friends}" var="entry">
    Key = ${entry.key}, value = ${entry.value}<br>
   </c:forEach>

如何显示对象memebers值。我的班级代码是

    package jmsg;

    public class friends {

        public String fullname;
        public String city;
        public String country;
        public String gender;

}

我有这样的输出

Key = 0, value = jmsg.friends@f2bf5b
Key = 1, value = jmsg.friends@1addae4
Key = 2, value = jmsg.friends@fdcc51

我想要像这样的数据结构

[0]
    "fulname" =>   "jhon"
    "city"    =>   "london"
    ""age"    =>   "23"

[1] 

     "fulname" =>   "Navi"
    "city"    =>   "Delhi"
    ""age"    =>   "23"

[1] 

     "fulname" =>   "Navi"
     "city"    =>   "Delhi"
     ""age"    =>   "21"

[2]
     "fulname" =>   "singh"
     "city"    =>   "Delhi"
     ""age"    =>   "26"

1 个答案:

答案 0 :(得分:0)

<c:forEach items="${friends}" var="entry">
    Key = ${entry.key},
    value = ${entry.value.fullname}, ${entry.value.city}, ${entry.value.age}<br>
</c:forEach>