Java – JSTL – iterating user-defined classes using foreach
•
Java
See English answer > javax servlet. ServletException: javax. servlet. jsp. Jsptagexception: don't know how to iterate over supplied "items" in < foreach > 2
For example, if I create a generic "projectset" class, I want to use the following tags in the JSP view:
<c:forEach items="${projectset}" var="project">
...
</c:forEach>
Basic class files:
public class ProjectSet {
private ArrayList<Project> projects;
public ProjectSet() {
this.projects = new ArrayList<Project>();
}
// .. iteration methods ??
}
Is there any interface I must implement, such as arrayaccess or iterator in PHP, to make it work?
Edit: there is no direct access to the ArrayList itself, because I may use a generic set class, and the JSP view should not know the internal work of the class
Solution
The Iterable interface provides this function:
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 swap iterator logic as needed
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
