6

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

Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
Parris
  • 17,833
  • 17
  • 90
  • 133
  • I won't put in a scriptlet answer (comment only) because you just shouldn't use them, but your scriptlet clearly won't compile. "new iter.next()" <== new shouldn't be there. You also either would need to use a typed Iterator or else put a (model.X) in front of iter.next(). – stevedbrown Apr 09 '10 at 13:54

1 Answers1

12

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
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 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 Apr 09 '10 at 08:10
  • 1
    no is part of the jstl tag lib...it's about as standard as you can get – Gareth Davis Apr 09 '10 at 08:19
  • @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 Apr 09 '10 at 09:24
  • 2
    @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 Apr 09 '10 at 12:21