我需要在JSP页面上展示一棵树,我有以下对象:
public class Node {
private Long id;
private Long parentId;
private String name;
private List<Node> children;
// Getters & setters
}
使用JSP递归自己来实现。
在Controller.java
文件中:
Node root = getTreeRootNode();
request.setAttribute("node", root);
在main.jsp
页面中
<jsp:include page="node.jsp"/>
在node.jsp
中
<c:forEach var="node" items="${node.children}">
<!-- TODO: print the node here -->
<c:set var="node" value="${node}" scope="request"/>
<jsp:include page="node.jsp"/>
</c:forEach>
基于http://web.archive.org/web/20130509135219/http://blog.boyandi.net/2007/11/21/jsp-recursion/。
从其他答案编译而来。已测试。
Unit.java
public class Unit {
private String name;
private HashSet<Unit> units;
// getters && setters
}
Employees.java
public class Employees {
private HashSet<Unit> units;
// getters && setters
}
Application.java
...
request.setAttribute("employees", employees);
request.getRequestDispatcher("EmployeeList.jsp").forward(request, response);
...
EmployeeList.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
<ul>
<c:forEach var="unit" items="${employees.getUnits()}">
<li>
<c:set var="unit" value="${unit}" scope="request"/>
<jsp:include page="Unit.jsp"/>
</li>
</c:forEach>
</ul>
</body>
<html>
Unit.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<span>${unit.getName()}</span>
...
<ul>
<c:forEach var="innerUnit" items="${unit.getUnits()}">
<li>
<c:set var="unit" value="${innerUnit}" scope="request"/>
<jsp:include page="Unit.jsp"/>
</li>
</c:forEach>
</ul>
http://beehive.apache.org/docs/1.0/netui/tagsTree.html
以下讨论可能会有所帮助。 http://www.jguru.com/faq/view.jsp?EID=46659