How can I go through a Set in JSP? (Hibernate Asso

2019-06-18 04:40发布

问题:

So I am pretty new to JSP. I have tried this a few ways. Ways that would make sense in PHP or automagicy frameworks... I am probably thinking too much in fact...

I have a hibernate one to many association. That is class x has many of class y. In class x's view.jsp. I would like to grab all of class y, where the foreign key of y matches the primary key of x and display them. It seems that hibernate properly puts this stuff into a set. Now, the question is how can I iterate through this set and then output it's contents...

I am kind of stumped here. I tried to write a scriptlet,

<%
java.util.Iterator iter = aBean.getYs().iter(); // aBeans is the bean name
// getYs would return the set and iter would return an iterator for the set
while(iter.hasNext) { 
   model.X a = new iter.next() 
%>
   <h1><%=a.getTitle()%></h1>
<%
}
%>

It would seem that that sort of thing should work? Hmmmmmm

回答1:

You'd better place the bean as request (or session) attribute and iterate over it using JSTL:

<c:forEach items="${bean.ys}" var="item">
   <h1>${item.title}</h1>
</c:forEach>