【问题标题】:toString() method not being executed when using JSTL [duplicate]使用 JSTL 时未执行 toString() 方法 [重复]
【发布时间】:2020-05-22 00:05:35
【问题描述】:

我有一个 ArrayList,其中包含一些类对象,这些对象在构造函数中采用变量,并带有 getter、setter 和 toString() 方法。因此,我想使用 JSTL 提供的 <c:forEach> 标记遍历该 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));
    %>
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 + "]";
    }
}

我在这里循环遍历 ArrayList:

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

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

一切似乎都很好,只是 toString() 方法不起作用。

【问题讨论】:

    标签: jsp jstl tostring


    【解决方案1】:

    尝试做这样的事情:

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

    【讨论】:

      猜你喜欢
      • 2015-02-17
      • 1970-01-01
      • 1970-01-01
      • 2015-06-03
      • 2011-01-20
      • 2015-11-01
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      相关资源
      最近更新 更多