views:

51

answers:

1

Hi All, 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

+4  A: 

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>
Bozho
does this mean I need to create my own TLD, and then have a foreach function, pass it the set of items, and then i guess it would set data to a variable you give it named 'item' (which you specified in var)? I am kind of lost to how this would work. Is there some library i need to pull from?
Parris
no <c:forEach> is part of the jstl tag lib...it's about as standard as you can get
Gareth Davis
@Parris you need a taglib declaration on the top of your file: <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> (different one if you're using xml encoded jsp's, of course). You can choose whatever prefix you want, but some containers automatically interpret anything with c: as coming from jstl core, which is why you don't always need the declaration.
wds
@Parris: how to install and use JSTL: http://stackoverflow.com/questions/2400038/enabling-javaserverpages-standard-tag-library-jstl-in-jsp/2401001#2401001 Another hint: do not use scriptlets. Get rid of them all. They are a poor practice in real world.
BalusC
Ahh, ok thanks :-D!
Parris