jjcode jjcode - 3 months ago 6x
SQL Question

Iterating through a List Object in JSP

I am working on a project to try and teach myself spring and struts. I am currently stuck on a JSP page. I have a pojo class with variables eid and ename with getters/setters, I also have a table in sql with the same values with six populated rows.
I am accessing my database through a

and have stored the result in a list, I then passed this list to my action page in which I set it as a
. In my jsp page I call that attribute and then try to iterate through it using
However nothing shows up, I know that my list variable has data in it since i checked it using the expression tag
and objects show up like this:


I thought that maybe I was missing something on jstl but I have jstl-1.2 in my
folder. I have also tried to add it in the configure path file and still nothing. I also have the correct tag url.
Also when I do a simple
<c:out value="Hello"/>
. Hello does print out. So this leads me to believe that my
is working properly, but when I try iterating through my list using
nothing shows up at all.

Anyways here is my JSP page:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO- 8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.List"%>
<!DOCTYPE html>
<% List eList = (List)session.getAttribute("empList");%>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee Details</title>
<c:out value="Hello"></c:out>
<h3>Employee Details</h3>
<hr size="4" color="gray"/>
<c:forEach items="${eList}" var="employee">
<td>Employee ID: <c:out value="${employee.eid}"/></td>
<td>Employee Pass: <c:out value="${employee.ename}"/></td>

Any help would be highly appreciated!


Before teaching yourself Spring and Struts, you should probably learn Java. Output like this


is the result of the Object#toString() method which all objects inherit from the Object class, the superclass of all classes in Java.

The List sub classes implement this by iterating over all the elements and calling toString() on those. It seems, however, that you haven't implemented (overriden) the method in your Employee class.

Your JSTL here

<c:forEach items="${eList}" var="employee">
        <td>Employee ID: <c:out value="${employee.eid}"/></td>
        <td>Employee Pass: <c:out value="${employee.ename}"/></td>  

is fine except for the fact that you don't have a page, request, session, or application scoped attribute named eList.

You need to add it

<% List eList = (List)session.getAttribute("empList");
   request.setAttribute("eList", eList);

Or use the attribute empList in the forEach.

<c:forEach items="${empList}" var="employee">
        <td>Employee ID: <c:out value="${employee.eid}"/></td>
        <td>Employee Pass: <c:out value="${employee.ename}"/></td>