我有一个 Servlet,它收集表单数据,进行数据库查询,检索数据,并将其放入哈希映射中。如下面:
ResultSet rs = d.execute(SQL);
// Get session and and create hash map (fhMap is flight-hash-map)
HttpSession session = request.getSession();
HashMap<Long, UserFlightsBean> fhMap = new HashMap<Long, UserFlightsBean>();
while(rs.next()) {
int FlightNumber = rs.getInt("FlightNumber");
String Operator = rs.getString("Operator");
String Source = rs.getString("Source");
String DepartureTime = rs.getString("DepartureTime");
String Destination = rs.getString("Destination");
String ArrivalTime = rs.getString("ArrivalTime");
int Cost = rs.getInt("Cost");
int Seats = rs.getInt("SeatsAvailable");
// Get session, get UserFlightsBean, set session UserFlightsBean
UserFlightsBean ufb = new UserFlightsBean(FlightNumber, Operator, Source, DepartureTime, Destination, ArrivalTime, Cost, Seats);
fhMap.put((long) FlightNumber, ufb);
System.out.println(FlightNumber + "t" + Operator + "t" + Source + "t" + DepartureTime + "t" + Destination + "t" + ArrivalTime + "t" + Cost + "t" + Seats + "t");
}
// Add hash map "fhMap" to session bean
session.setAttribute("fhMap", fhMap);
如您所见,我使用查询创建了一个对象,数据库中的每一行都是我放入哈希映射的对象,然后将哈希映射添加到会话中,以便我可以在我的 jsp 页面上访问它。
在jsp页面上,我得到了会话哈希映射,现在我正在尝试打印出对象的元素,这就是我的问题所在。我的 jsp 页面代码如下:
<%
HashMap <Long, UserFlightsBean> printMap = (HashMap <Long, UserFlightsBean>)session.getAttribute("fhMap");
pageContext.setAttribute("objects", printMap);
%>
<c:forEach items="${objects}" var="entry">
Key is ${entry.key} <%-- these two for testing purposes --%>
value = ${entry.value}<br>
<ul>
<c:forEach var="junk" items="${value.UserFlightsBean}">
<li>${junk.getFlightNumber()}</li>
</c:forEach>
</ul>
</c:forEach>
所以我要做的是打印(到<li>
中)该对象中包含的所有变量。我在网上到处搜索,搜索堆栈溢出水域,但找不到如何做到这一点。
感谢您提供的任何帮助!
在这里,我能理解的是,你不需要使用内部循环......你可以像这样编写代码:
`<c:forEach items="${objects}" var="entry">
Key is ${entry.key} <%-- these two for testing purposes --%>
<ul>
<li>${entry.value.getFlightNumber()}</li>
<li>${entry.value.getOperator()}</li>
<li>${entry.value.getSource()}</li>
</ul>
</c:forEach>`