0

I have an ArrayList with some class objects which take on variables in the constructor and with getters, setters and a toString() method. So I want to loop through that ArrayList with the <c:forEach> tag provided by JSTL. The toString() method doesn't seems to do its job though.

    <% //adding data to arraylist
    List<Student> dataList = new ArrayList<Student>();
    dataList.add(new Student("John", "Doe", false));
    dataList.add(new Student("El", "Chappo", false));
    dataList.add(new Student("Ciano", "Mehdol", false));
    dataList.add(new Student("Lereone", "Zuba", true));
    %>
Public class Student { //basic model class with constructor, getters/setters, toString() method

    private String firstName;
    private String lastName;
    private boolean goldCustomer;
    
    public Student(String firstName, String lastName, boolean goldCustomer) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.goldCustomer = goldCustomer;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public boolean isGoldCustomer() {
        return goldCustomer;
    }

    public void setGoldCustomer(boolean goldCustomer) {
        this.goldCustomer = goldCustomer;
    }

    @Override
    public String toString() {
        return "Student [firstName=" + firstName + ", lastName=" + lastName + ", goldCustomer=" + goldCustomer + "]";
    }
}

And here I'm looping through the ArrayList:

<c:forEach var="listLoop" items="<%= dataList %>">
${listLoop}

<br/><br/>
</c:forEach>

Everything seems fine except that the toString() method doesn't work.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
syclone
  • 99
  • 13

1 Answers1

0

Try to do something like this:

<% //adding data to arraylist
List<Student> dataList = new ArrayList<Student>();
dataList.add(new Student("John", "Doe", false));
dataList.add(new Student("El", "Chappo", false));
dataList.add(new Student("Ciano", "Mehdol", false));
dataList.add(new Student("Lereone", "Zuba", true));

pageContext.setAttribute("list", dataList); <%-- to reference list into page scope --%>
%>
...

<c:forEach var="student" items="${list}">
     <c:out value="${student}"/>
</c:forEach>
Anthony
  • 571
  • 3
  • 11