JSTL - 使用 forEach 迭代用户定义的类
我需要向自定义 Java 类添加哪些方法,以便可以迭代其成员之一中的项目?我找不到任何关于 JSTL forEach 标签如何实际工作的规范,所以我不确定如何实现它。
例如,如果我创建了一个通用的“ProjectSet”类,并且我想在 JSP 视图中使用以下标记:
<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
或 < code>Iterator 为了让它工作?
编辑:无需直接访问 ArrayList 本身,因为我可能会使用某种使用泛型的 Set 类,并且 JSP 视图不必了解该类的内部工作原理。
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.
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>
Basic class file:
public class ProjectSet {
private ArrayList<Project> projects;
public ProjectSet() {
this.projects = new ArrayList<Project>();
}
// .. iteration methods ??
}
Is there any interface that I must implement like PHP's ArrayAccess
or Iterator
in order for this to work?
Edit: 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Iterable 接口提供了此功能:
您可以根据需要交换迭代器逻辑。
The Iterable interface provides this functionality:
You can exchange the iterator logic as you need.
是的,您应该实现 java.util.Iterable
Yes, you should implement java.util.Iterable
不幸的是,
forEach
标签不支持Iterable
作为项目源。它支持:Collection
Iterator
Enumeration
Map
String 中给出的以逗号分隔的值列表
(相关源代码:ForEachSupport)
其中,最好使用
Iterator
作为forEach
源,当您希望从您自己的类中获取项目时。Unfortunately, the
forEach
tag does not supportIterable
as the items source. It does support:Collection
Iterator
Enumeration
Map
String
(relevant source code: ForEachSupport)
Of these, it's probably best to use an
Iterator
as theforEach
source when you wish to fetch items from your own class.