13 December 2008

How to iterate over a collection using struts logic taglib

Among struts Tag libararies there's a taglib called logic, it aims to do logical operation especially values and strings comparison using its tags such as Equa, NotEqaul, present, notPresent, greaterThan and more.

Among theses tags, there is a very handy tag that used to iterate over collection, it remembers me with the JSTL forEach tag, but it provides more funcationality.

We can use this tag to display the model data as it appears in the next view in very easy-to-use way :

lets illustrate it, assume we have an abject called EmployeeBO that wrap and Employee object of four attributes : ssn, firstname, lastname and age.

The EmployeeBO object contains a method called getAllEmployees that returns an array list of employees objects.
The following code is the code of the action class, it inserts the result of "getAllEmployees" in the session to get it back again in the view from the session:

package org.daz;

import javax.servlet.http.*;
import java.util.*;
import org.apache.struts.action.*;

public class GetAllEmployeesAction extends org.apache.struts.action.Action {

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

ActionForward forward = null;

EmployeeBO emps = new EmployeeBO();
List empList = emps.getAllEmployees();

HttpSession session = request.getSession();
session.setAttribute("empList", empList);

forward = mapping.findForward("success");

return forward;
}
}


and this is the code of the jsp page:

<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>

<%@taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>

<html:html>

<head>

<html:base />

</head>

<body>

<table border="1" width="50%">

<tr>

<td>serial</td>

<td>SSN</td>

<td>First name</td>

<td>Last name</td>

<td>Age</td>

</tr>

<logic:iterate id="employee"
name="empList" indexId="id" offset="${param.offset}" length="5">

<tr>

<td>${id }</td>

<td>${employee.ssn }</td>

<td>${employee.firstname }</td>

<td>${employee.lastname }</td>

<td>${employee.age }</td>

</tr>

</logic:iterate>

</table>

<html:link href="showemps.jsp?offset=${id - 9}"> previous </html:link>

<html:link href="showemps.jsp?offset=${id+1}"> next </html:link>

</body>

</html:html>

The logic tag appears in red, it takes more than one attribute;

id: an page-scoped object that will store the current iteration object

name : the name of the scopped bean to iterate over

indexId : an page-scoped object that will store the current iteration number

offset : the index of the collection to start from

length : the number of rows to display on a page

2 comments:

Anonymous said...

thanks for the post. It helped me to clear my doubt

mhewedy said...

You are very welcome.
thats my hope to aid others :)