Iterator tag : Struts 2

Posted on September 03, 2014
Iterator tag is used to iterate values in the form of any java collection or array. You can easily find iterator tag with Java Collections but here I am implementing how to use Iterator tag with Array Object in Struts 2. What is in demo code? Iterate list of bean which contain
  1. Another bean,
  2. List of string, and
  3. A List of bean.
And also demonstrate how to fin size of the list in struts 2 UI tag. Iteration of list of string is bit tricky. You can iterate list of string with count of the iterator. For e.g. If you want to List<String> email, then you can do this like,
<s:iterator value="emails" begin="0" status="number">
    <s:property value="email[#number.count - 1]" />
</s:iterator>
Bean : Address.java
package com.vivekpatidar.beans;

/**
 * @author Vivek Patidar
 */

public class Address {

    private String city;
    private String state;
    private String country;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Override
    public String toString() {
        return "Address [city=" + city + ", state=" + state + ", country="
                + country + "]";
    }

}
Bean : Education.java
package com.vivekpatidar.beans;

/**
 * @author Vivek Patidar
 */

public class Education {

    private String degree;
    private String year;
    private String grade;

    public String getDegree() {
        return degree;
    }

    public void setDegree(String degree) {
        this.degree = degree;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

    @Override
    public String toString() {
        return "Education [degree=" + degree + ", year=" + year + ", grade="
                + grade + "]";
    }

}
This is the user bean which contains list of string and bean
package com.vivekpatidar.beans;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Vivek Patidar
 */

public class User {

    private Integer id;
    private String name;
    
    /**
     * List of string
     */
    private List<String> emails = new ArrayList<String>();
    
    /**
     * Address bean
     */
    private Address address = new Address();
    
    /**
     * List of Education bean
     */
    private List<Education> educations = new ArrayList<Education>();

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getEmail() {
        return emails;
    }

    public void addEmail(String email) {
        this.emails.add(email);
    }

    public List<String> getEmails() {
        return emails;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public List<Education> getEducations() {
        return educations;
    }

    public void addEducation(Education educations) {
        this.educations.add(educations);
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", emails=" + emails
                + ", address=" + address + ", educations=" + educations + "]";
    }

}
This is action class of struts
package com.vivekpatidar.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;

import com.vivekpatidar.beans.Education;
import com.vivekpatidar.beans.User;

/**
 * This is the action which contain list of user and this user contain another
 * list of string (email list), another bean (Address bean) and another list of
 * bean (Education bean).
 *
 * @author Vivek Patidar
 */

@Namespace("/user")
@Action("/allUsers")
@Result(location = "users.jsp", name = "success")
public class UserAction {

    private List<User> users;

    public List<User> getUsers() {
        return this.users;
    }

    public String execute() throws Exception {

        this.users = new ArrayList<User>();

        /**
         * Creating detail for first user.
         */
        User user = new User();
        user.setId(101);
        user.setName("User 1");
        user.addEmail("user_1_first@gmail.com");
        user.addEmail("user_1_second@gmail.com");

        // set address of the first user
        user.getAddress().setCity("Indore");
        user.getAddress().setState("Madhya Pradesh");
        user.getAddress().setCountry("India");

        // First education of the first user
        Education education = new Education();
        education.setDegree("B.Sc");
        education.setGrade("B+");
        education.setYear("2012");
        user.addEducation(education);

        // Second education of the first user
        education = new Education();
        education.setDegree("M.Sc");
        education.setGrade("A");
        education.setYear("2014");
        user.addEducation(education);

        this.users.add(user);

        /**
         * Creating detail for second user.
         */
        user = new User();
        user.setId(102);
        user.setName("User 2");
        user.addEmail("user_2_first@gmail.com");
        user.addEmail("user_2_second@gmail.com");

        // set address of the second user
        user.getAddress().setCity("Bhopal");
        user.getAddress().setState("Madhya Pradesh");
        user.getAddress().setCountry("India");

        // First education of the second user
        education = new Education();
        education.setDegree("B.Com.");
        education.setGrade("B");
        education.setYear("2011");
        user.addEducation(education);

        // Second education of the second user
        education = new Education();
        education.setDegree("M.Com.");
        education.setGrade("A");
        education.setYear("2013");
        user.addEducation(education);

        this.users.add(user);

        return "success";
    }

}
index.jsp file
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML>
<html>
<head>
<title>Iterator Tag</title>
<style type="text/css">
body {
    font-size: 20px;
}
</style>
</head>
<body>
    <div style="text-align: center;">
        <h2>Struts2 UI - Iterator Tag</h2>
    </div>
    <div>
        <%-- Here is the code for find size of list --%>
        Total Users = <s:property value="#request['users'].size" />
        <hr />
        <br />
        <s:iterator value="#request['users']">
            Id : <s:property value="id" /><br />
            Name : <s:property value="name" /><br />

            <%-- This will iterate the Email list of string  --%>
            <s:iterator value="emails" begin="0" status="number">
                Email <s:property value="#number.count" /> : <s:property value="email[#number.count - 1]" /><br />
            </s:iterator>

            <br /><u>Address Bean:</u><br />
            
            <%-- This is the Address bean in the user --%>
            City : <s:property value="address.city" /><br />
            State : <s:property value="address.state" /><br />
            Country : <s:property value="address.country" /><br />

            <br /><u>List of Education Bean:</u><br />
            
            <%-- This will iterate Education list of the user --%>
            <s:iterator value="educations" status="number">
                Education <s:property value="#number.count" /><br/>
                Degree : <s:property value="degree" /><br/>
                Year : <s:property value="year" /><br/>
                Grade : <s:property value="grade" /><br/>
                <br />
            </s:iterator>
            <hr />
        </s:iterator>
    </div>
    
    <div style="text-align: right">
        <h5>
            Developed by : Vivek Patidar <br /> Email : vivekpatidar1@gmail.com
        </h5>
    </div>
</body>
</html>
web.xml File
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>iterator</display-name>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>