How to iterate an object over a list of objects in JSTL?

南楼画角 提交于 2019-12-24 06:47:17

问题


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.



来源:https://stackoverflow.com/questions/8711251/how-to-iterate-an-object-over-a-list-of-objects-in-jstl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!