How to iterate an object over a list of objects in

2019-08-10 12:06发布

问题:

I have a class named Language with 1 field named name. I have another class named Speech which has a language member. I need to iterate over a list of Speech objects. In JSTL:

<c:forEach items="${requestScope.Speech}" var="speech">
  <tr>
    <td>&nbsp;${speech.id}</td>
    <td>&nbsp;${speech.language.name}</td>
  </tr> 
</c:forEach>

My second statement ${speech.language.name} doesn't work. How can I make it work?

Speech and Language classes:

public class Speech {
    private int id;
    private Language language=null;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public Language getLanguage() {
        return language;
    }
    public void setLanguage(Language language) {
        this.language = language;
    }
}

public class Language {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    } 
}

回答1:

Make sure that your Speech class has a public Language getLanguage() method defined.



回答2:

The JSP EL doesn't use fields. It uses properties. In order for this statement to work, you need to have a public method getLanguage() in Speech, and a public method getName() in Language.

EDIT:

If the getters are there, and nothing is being printed, it can have four reasons:

  • there is no Speech attribute in the request
  • there is a list of Speeches in the Speech request attribute, but this list is empty
  • the language of each Speech of the list is null
  • the name of each Language is null or blank.

If something is printed for the speech ID, it eliminates the first two reasons.



标签: java jstl