PROGRAMS

Display ArrayList elements using Iterator in JSP

In this example, a user requests to display employee’s data belonging to an organization on a UI (JSP).  This example uses the MVC architecture. Following steps summarizes this example. 

  1. The JSP contains a link to request for the employee data (View)
  2. The request is sent to a Java servlet (Controller)
  3. The servlet calls a DAO class to execute the business logic. In our case, it is to fetch employee data (Model)
  4. The request again sent to the JSP to display the employee data. The data is held in the ArrayList here.
  5. Next, display ArrayList elements using Iterator in JSP.

The following image explains the files/classes used in this example. Do note that, you would need servlet-api.jar to add dependencies for the Java servlet. We are using the Eclipse Integrated development environment(IDE) for this example. You can get one for free from here. To begin with, go to File > New > Dynamic Web Project

Directory Structure

Suggested Read:

<%--Iterator.jsp --%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%@page import="java.util.ArrayList"%>      <%--Importing all the dependent classes--%>
<%@page import="com.dao.EmployeeDetails"%>
<%@page import="java.util.Iterator"%> 

<% ArrayList<EmployeeDetails> employeeList = (ArrayList) request.getAttribute("EmpList"); %> <%--Assigning ArrayList object containing Employee data to the local object --%>

<strong><a href="<%=request.getContextPath()%>/IteratorExample?type=getDetails">Show Employee Details</a></strong>
<br></br>

<table cellspacing="2" cellpadding="2">

<tr><th>Employee ID</th><th>Employee Age</th><th>Employee Name</th><th>Employee City</th></tr>
<%
// Iterating through subjectList

if(request.getAttribute("EmpList") != null)  // Null check for the object
{
 Iterator<EmployeeDetails> iterator = employeeList.iterator();  // Iterator interface
 
 while(iterator.hasNext())  // iterate through all the data until the last record
 {
  EmployeeDetails empDetails = iterator.next(); //assign individual employee record to the employee class object
 %>
 <tr><td><%=empDetails.getEmployeeID()%></td>
  <td><%=empDetails.getEmployeeAge()%></td>
  <td><%=empDetails.getEmployeeName()%></td>
  <td><%=empDetails.getEmployeeCity()%></td>
 </tr>
 <%
 }
}
%>
</table>

</body>
</html>

IteratorExample.java

//IteratorExample.java
package com.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dao.EmployeeDetails;

public class IteratorExample extends HttpServlet {
 private static final long serialVersionUID = 1L;

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  System.out.println("Inside Servlet"); 
   
  String type = request.getParameter("type");
  
  if(type.equals("getDetails"))
  {
        
    EmployeeDetails empDetails = new EmployeeDetails(0, 0, type, type);
    
    empDetails.getEmployeeDetails();
    
    request.setAttribute("EmpList", empDetails.getEmployeeDetails());
  
    request.getRequestDispatcher("JSP/Iterator.jsp").forward(request, response);     
  }
 }
}

The following class EmployeeDetails.java pushes the employee data into the arraylist object. Please note that you can also use a database connection to read employee data and assign it to the arrayList object. You can also make use of JavaBeans to play with the employee attributes. You can go through the following links to understand how you can connect to a database and use JavaBeans. Login application in Java and Registration application in Java.

//EmployeeDetails.java
package com.dao;

import java.util.*;

public class EmployeeDetails {
 
 private int employeeID;
 private int employeeAge; 
 private String employeeName;
 private String employeeCity;
 
 //Parameterized Constructor
  public EmployeeDetails(int id, int age, String name, String city)
  {
   this.employeeID = id;
   this.employeeAge = age;
   this.employeeName = name;
   this.employeeCity = city;
  }
  
  public int getEmployeeID() {
   return employeeID;
  }
  public int getEmployeeAge() {
   return employeeAge;
  }
  public String getEmployeeName() {
   return employeeName;
  }
  public String getEmployeeCity() {
   return employeeCity;
  }

 public ArrayList<EmployeeDetails> getEmployeeDetails()
 {
  ArrayList<EmployeeDetails> empList = new ArrayList<EmployeeDetails>();
   
  empList.add(new EmployeeDetails(1, 20, "Ram", "Delhi"));  //Adding employee data to the ArrayList object via parameterized constructor
  empList.add(new EmployeeDetails(2, 30, "Raj", "Mumbai"));
  empList.add(new EmployeeDetails(3, 40, "Ron", "Pune"));
  empList.add(new EmployeeDetails(4, 50, "Rob", "Belgaum"));
  empList.add(new EmployeeDetails(5, 60, "Roy", "Bengaluru"));
   
   for (EmployeeDetails s : empList) //Iterates as long as there are elements in the list.
   {
    System.out.print("ID, Name and City of the employee are : ");
    System.out.println(s.employeeID + " " + s.employeeAge + " " + s.employeeName + " " + s.employeeCity);
   }
  return empList;
 }
}

The web.xml contains the servlet information. This file gets loaded in the beginning when you run your project. This is also known as deployment descriptor. It can also contain additional tags to define the session interval, welcome file lists and many more.

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Iterator Example</display-name>
  <welcome-file-list>
    <welcome-file>JSP/Iterator.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>IteratorExample</display-name>
    <servlet-name>IteratorExample</servlet-name>
    <servlet-class>com.controller.IteratorExample</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>IteratorExample</servlet-name>
    <url-pattern>/IteratorExample</url-pattern>
  </servlet-mapping>
</web-app>

The following image explains how the Employee data looks like on the UI dashboard (JSP).

JSP showing the end result

Ravi Bandakkanavar

A Techie, Blogger, Web Designer, Programmer by passion who aspires to learn new Technologies every day. A founder of Krazytech. It's been 10+ years since I am publishing articles and enjoying every bit of it. I want to share the knowledge and build a great community with people like you.

Leave a Comment
Share
Published by
Ravi Bandakkanavar

Recent Posts

Everything You Need To Know About Create React App

The configuration of resources can be a time-consuming and difficult operation while creating a React…

3 weeks ago

Causes of CyberCrime and Preventive Measures

          Rapid technological growth and developments have provided vast areas of…

1 month ago

How Data Lineage will Improve Business Practices

How often have you thought about changing the way that you store and use data?…

1 month ago

10 Dominating Programming Language for Mobile App In 2022

Programming Languages are a set of rules that aid in transforming a concept into a…

1 month ago

What is Serverless Edge Computing? Features | Benefits

Serverless edge computing is a new technology with a lot of promise, but it can…

1 month ago

Are Your Accounts Protected Against Cyberattacks?

Do any of your passwords include personal names, date of birth, or pet names? If…

2 months ago