JSTL - 使用 forEach 迭代用户定义的类
我需要向自定义 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.
相关文章