Thursday, February 26, 2009

Iteration/Iterator in Struts 2

This blog post intends to answer the following questions :-
  1. How to iterate over a collection using Struts 2?
  2. How to display the contents of an ArrayList in struts 2 on a jsp page?
  3. How to access the servlet context object from Struts 2?
iterating over a collection is an easy task in Struts 2. All that you need to do is to user the iterator tag. This tag is well designed to loop over any Collection/map/iterator/array/enumeration.

In the following example in I demonstrate how to make use of the iterator tag to iterate over an ArrayList that is stored in the servlet context.

MyPage.jsp
------Start Of Source Code------
...
...
<s:iterator value="#application.userDetailsList">
<s:property value="userName"/>
<br/>
</s:iterator>

...
...
------End of source Code------

Explanation :-
In the above example, I try to retrieve an ArrayList from the servlet context object using. The servelt context object can be accessed from a jsp page by using the '#application'. the ArrayList was stored in the servlet context as an attribute with the binding name as-'userDetailslist'. This Arraylist contained a large number of 'UserDetails' objects. Each UserDetails object has a property called -'userName'. So the above example iterated over all the UserDetails objects in the ArrayList and prints the userName for each every iteration.

I guess it couldn't get anymore simpler than this!

Happy Programming ;)

Signing Off
Ryan

No comments: