Wednesday, February 11, 2009

JSTL c:forEach tag

JSTL (JSP Standard Tag Libraries) make it easier to iterate arrays, list or a set. The c:forEach tag is a core tag in JSTL library and also one of most useful tag. I can be used to create HTML tables, generating XML and many more. Following examples elaborate more how <c:forEach> tag could be used to generate an HTML table and generating an XML.

Example:

student is an object of Student class(see below). A group of students can be represented in a Array or List.

List <Student> students = new ArrayList <Student> (10);
Student s1 = new Student();
students.add(s1);

Student s2 = new Student();
students.add(s2);

...
...

<html>
<head>
    <title>c:forEach example </title>
</head>
<body>
    <table>
        <c:forEach var="student" items="${students}">
            <tr>
                <td>${student.id}</td>
                <td>${student.name}</td>
                <td>${student.major}</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

Example2:

List lists = new ArrayList();

List <String> list1 = new ArrayList <String> ();
list1.add("A");
list1.add("B");
list1.add("C");

lists.add(list1);

List <String> list2 = new ArrayList <String> ();
list2.add("AA");
list2.add("BB");
list2.add("CC");

lists.add(list2);

...
...

<html>
<head>
    <title>c:forEach example </title>
</head>
<body>
    <table>
        <c:forEach var="list" items="${lists}">
            <tr>
                <td>${list[0]}</td>
                <td>${list[1]}</td>
                <td>${list[2]}</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

Example 3:

Generating XML from students object:

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<?xml version="1.0" encoding="utf-8"?>
<rows>
    <c:forEach var="student" items="${students}">
        <row>
            <cell><![CDATA[${student.id}]]> </cell>
            <cell><![CDATA[${student.name}]]> </cell>
            <cell><![CDATA[${student.major}]]> </cell>
        </tr>
    </c:forEach>
</rows>

Class Student{
    private int id;
    private String name;
    private String major;
    public Student(){
        id=0;
        name="";
        major="";
    }
    public void setId(int id){
        this.id = id;
    }
    public void setName(String name{
        this.name = name;
    }
    public void setMajor(String major){
        this.major = major;
    }
    public int getId(){
        return this.id;
    }
    public String getName(){
        return this.name;
    }
    public String getMajor(){
        return this.major;
    }
}

No comments: