It's not a secret anymore!
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes jsp:useBean && forEach Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "jsp:useBean && forEach" Watch "jsp:useBean && forEach" New topic

jsp:useBean && forEach


Joined: Sep 14, 2005
Posts: 10

The below code works fine using JSTL

<H3> This is an example for JSTL </H3>
<c:forEach var = "myBean" items= "${requestScope.LukeObject}" varStatus ="MyBeanCounter">
Bean value of ${MyBeanCounter.count} is ${myBean.intA}

This is an example for JSTL
Bean value of 1 is 0 Bean value of 2 is 1 Bean value of 3 is 2

But the below code is not working (useBean && JSTL combination)

<H3> This is an example for useBean </H3>
<jsp:useBean id ="myJSPBean" class ="Foo.Bean" scope ="request"/>
<c:forEach var ="myJSPBearVar" begin = "1" step = "1" items = "${myJSPBean}">
Bean value of ${begin} is ${myJSPBearVar.intA}

I get the below error

javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in <forEach>

Can any one help me out how to use useBean and forEach together?

[ October 11, 2005: Message edited by: Luke ]
Mat Williams
Ranch Hand

Joined: Jul 20, 2005
Posts: 215
Hi Luke,

for this line to work
<jsp:useBean id ="myJSPBean" class ="Foo.Bean" scope ="request"/>

it requires an object stored in the request under the name "myJSPBean". That is the servlet will need to have done the following

then in the JSP, the useBean tag will get that bean and make it available to other tags. If the servlet has not created it the useBean tag will create it for you.

when you get to this bit
<c:forEach var ="myJSPBearVar" begin = "1" step = "1" items = "${myJSPBean}">

the EL ${myJSPBean} will go looking for an object in some scope with that name which makes the useBean completely redundant.

The jsp tags where thought of and created before EL and so you needed a way to get and set properties on beans etc, this is what the <jsp:...> tags do. These days EL mostly replaces the need to use the <jsp:...> tags.


Troy Peter

Joined: Oct 13, 2005
Posts: 14
Hi Luke, hi Mat,

Mat just gave a very good answer to your question. I'd like to add that the class Foo.Bean should be a collection for the tag c:forEach to work.

I agree. Here's the link:
subject: jsp:useBean && forEach
It's not a secret anymore!