Anand
Anand

Reputation: 10400

How to iterate over an array list of beans in a JSP using struts2 tags

My JSP receives an ArrayList of beans from a Struts2 action.

I want to iterate over them and print every bean and its properties per line.

How can I do this using Struts2 tags?

Upvotes: 4

Views: 12888

Answers (5)

Rohan
Rohan

Reputation: 5431

I did something similar in my basic application.

Here searchForm is bean and ArrayList is results

<logic:present name="searchForm" property="results">
    <bean:size id="size" name="searchForm" property="results"/>
   <logic:greaterThan name="size" value="0">
       <logic:iterate id="res" name="searchForm" property="results">
         <p>
         <bean:write name="res" property="firstname" />
         <bean:write name="res" property="lastname" />
         </p>
       </logic:iterate>
   </logic:greaterThan>
</logic:present>

Upvotes: 0

Nicola Baldissin
Nicola Baldissin

Reputation: 94

To do this with struts2 you need iterator:

<s:iterator value="collection">
Describe object
</s:iterator>

But I suggest to use displaytag: http://www.displaytag.org/1.2/ With only 1 row it describes all the bean and you can do also sorting and export. Here an example of use:

<display:table name="collection" />

and it generate a table, a thead and the tbody.

Upvotes: 1

coding_idiot
coding_idiot

Reputation: 13734

Here is a working example(Netbeans 6.9 project) illustrating how to iterate over an array or list of objects.

Also, how to submit the form such that the list of objects gets re-created on submission.

Simply resolve the references and get going.

Upvotes: 0

Bozho
Bozho

Reputation: 597124

Using JSTL:

<c:forEach items="${list}" var="item">
    <c:out value="${item.property}" />
</c:forEach>

You will have to add JSTL to the classpath, because it isn't shipped with Struts, but it shoul work. Of course, using struts' own tag (as shown by BalusC) is a better option.

Upvotes: 2

BalusC
BalusC

Reputation: 1108802

Use <s:iterator> tag.

<s:iterator value="beans">
     <p>Property foo: <s:property name="foo" /></p>
     <p>Property bar: <s:property name="bar" /></p>
</s:iterator>

An overview of all tags can be found in their own documentation: tag reference. Bookmark it.

Upvotes: 6

Related Questions