JSTL - 使用forEach迭代用户定义的类 [英] JSTL - Using forEach to iterate over a user-defined class
问题描述
我需要将哪些方法添加到自定义Java类中,以便我可以遍历其中一个成员中的项目?我找不到关于JSTL forEach标签实际如何工作的任何规范,所以我不确定如何实现它。
What methods do I need to add to a custom Java class so that I can iterate over the items in one of its members? I couldn't find any specifications about how the JSTL forEach tag actually works so I'm not sure how to implement this.
例如,如果我做了一个通用的 ProjectSet我和我想在JSP视图中使用以下标记:
For example, if I made a generic "ProjectSet" class and I woud like to use the following markup in the JSP view:
<c:forEach items="${projectset}" var="project">
...
</c:forEach>
基本类文件:
public class ProjectSet {
private ArrayList<Project> projects;
public ProjectSet() {
this.projects = new ArrayList<Project>();
}
// .. iteration methods ??
}
我是否必须实现任何接口,如PHP的 ArrayAccess
或 Iterator
以使其正常工作?
Is there any interface that I must implement like PHP's ArrayAccess
or Iterator
in order for this to work?
编辑:不直接访问ArrayList本身,因为我可能会使用泛型使用某种类的Set类,而JSP视图不应该知道类的内部工作原理。
Without directly accessing the ArrayList itself, because I will likely be using some sort of Set class using generics, and the JSP view shouldn't have to know about the inner workings of the class.
推荐答案
Iterable接口提供此功能:
The Iterable interface provides this functionality:
public class ProjectSet implements Iterable<Project> {
private ArrayList<Project> projects;
public ProjectSet() {
this.projects = new ArrayList<Project>();
}
// .. iteration methods ??
@Override
public Iterator<Project> iterator() {
return projects.iterator();
}
}
您可以根据需要更换迭代器逻辑。
You can exchange the iterator logic as you need.
这篇关于JSTL - 使用forEach迭代用户定义的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!