[toString()使用JSTL时未执行方法

问题描述 投票:0回答:1

我有一个ArrayList,其中包含一些类对象,这些类对象在构造函数中具有变量,并具有getter,setter和toString()方法。所以我想用JSTL提供的标签遍历那个ArrayList。 toString()方法似乎不起作用。

<% //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));
%>

公共类Student {//具有构造函数,getters / setters,toString()方法的基本模型类

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 + "]";
}

}

这里我正在遍历ArrayList:

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

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

除了toString()方法不起作用外,其他一切看起来都很好。

jsp jstl tostring
1个回答
0
投票

尝试做这样的事情:

<% //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>
© www.soinside.com 2019 - 2024. All rights reserved.