最近需要用一个在网页上显示一个树形的结构,原来的javascript脚本不是很适合,就是用了xloadtee,这个东西还是很好用的,
虽然还有一点点瑕疵,但是已经很好的达到了我的要求。
大概需要做的工作:
脚本引用:
<link type="text/css" rel="stylesheet" href="<%=request.getContextPath()%>/js/xtree2.css">
<link type="text/css" rel="stylesheet" href="<%=request.getContextPath()%>/js/xtree2.links.css">
<script type="text/javascript" src="<%=request.getContextPath()%>/js/xtree2.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/xloadtree2.js"></script>
使用个div在页面显示整个树:
<div style="position: absolute; width: 200px; top: 10px; left: 15px; height: 100%; padding: 5px; overflow: auto;">
<!-- js file containing the tree content, edit this file to alter the menu,
the menu will be inserted where this tag is located in the document -->
<script type="text/javascript">
var tree = new WebFXTree("组织结构树");
tree.showRootNode = false;
tree.showRootLines = false;
tree.add(new WebFXLoadTreeItem("系统", "/sectiontree.do"));
tree.expandAll();
tree.write();
</script>
</div>
页面部分即可完成,下面是服务器端的代码:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.setContentType("text/xml; charset=gbk");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
PrintWriter out = response.getWriter();
String id = request.getParameter("id");
Session ss = SessionHolder.getSessionHolder().currentSession();
Document doc = new Document(new Element("tree"));
if (id == null) {
// 取得根节点
String root = "select s from Section s inner join fetch s.children where s.parent.section_id is null";
Query query = ss.createQuery(root);
transfer(doc, query);
} else {
// 取得当前节点的id
int sid = Integer.parseInt(id);
String child = " from Section s where s.section_id=:id";
Query query = ss.createQuery(child);
query.setInteger("id", sid);
transfer(doc, query);
}
SessionHolder.getSessionHolder().closeSession(ss);
Format format = Format.getCompactFormat();
format.setEncoding("gbk");
format.setIndent("/t");
XMLOutputter xout = new XMLOutputter(format);
xout.output(doc, out);
out.flush();
out.close();
return null;
}
private void transfer(Document doc, Query query) {
List r = query.list();
Section s = (Section) HibernateUtil.uniqueResult(r);
for (Iterator it = s.getChildren().iterator(); it.hasNext();) {
Section one = (Section) it.next();
Element tree = doc.getRootElement();
Element inner = new Element("tree").setAttribute("text", one
.getName());
tree.addContent(inner);
if (!one.isLast())
inner.setAttribute("src", "/TechCS/sectiontree.do?id="
+ one.getSection_id());
inner.setAttribute("action", "javascript:setsection("
+ one.getSection_id() + ")");
}
}
以上部分就可以完成树结构的服务器部分。
说明:使用struts+hibernate。