JSTL - Using forEach to iterate over a user-defined class(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.
这篇关于JSTL - 使用 forEach 迭代用户定义的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JSTL - 使用 forEach 迭代用户定义的类
基础教程推荐
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
