1,首先是导入struts2的jar包和json的jar包(json包也是必须的),因为zTree是通过json数据和后台交互的,所以json是必须得
2,创建一个jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<script language="javascript" src="${pageContext.request.contextPath}/js/jquery-1.7.2.js"></script><!-- jquery的js包 -->
<script language="javascript" src="${pageContext.request.contextPath}/js/jquery-ztree-2.5.js"></script><!-- 使用zTree需要引入的js -->
<script language="javascript" src="${pageContext.request.contextPath}/js/js-ztree.js"></script> <!-- 自己写的js -->
<link rel="stylesheet" href="${pageContext.request.contextPath}/js/zTreeStyle/zTreeStyle.css" type="text/css"><!-- zTree自带的css样式 -->
<html>
<head>
<title>My JSP 'zTree.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<!-- 此table是在下载zTree官网文档的Demo,为左侧表 -->
<TABLE border=0 height=600px align=left>
<TR>
<TD width=230px align=left valign=top style="BORDER-RIGHT: #999999 1px dashed">
<ul id="tree" class="tree" style="width:230px; overflow:auto;"></ul>
</TD>
</TR>
</TABLE>
</body>
</html>
3,以下是上图中引入的js-ztree.js
zTree.jsvar zTree = {
setting: {
isSimpleData: true, //设置为简单类型
treeNodeKey: "mid", //主键id
treeNodeParentKey: "pid", //父节点
showLine: true, //是否展开
root: {
isRoot: true,
nodes: []
}
},
/**
* 在此加载树的内容,通过回调函数,将后台返回的json数据数据动态显示到id为tree的地方
*/
loadTree: function(){
$.post("menuitemAction_showMenuitems", null, function(data){
$("#tree").zTree(zTree.setting, data.menuitemList);
//alert(data.menuitemList);
});
}
};
/**
* 页面加载完后运行
*/
$().ready(function(){
//一次性加载树
zTree.loadTree();
});
4, 在struts的action类中将menuitemList声明成成员变量
private Collection<Menuitem> menuitemList;//并增加get/set方法
public String showMenuitems(){
this.menuitemList = this.menuitemService.showMenuitems();
return "success";
5,在struts.xml中配置
<package name="menuitem" namespace="/" extends="json-default">
<action name="menuitemAction_*" method="{1}" class="menuitemAction">
<result type="json"></result>
</action>
</package>
注意:extends="json-default"因为页面是ajax的回调函数获取后台数据的,所以只指定result type=“json”,就OK了
6, 6,为了防止session过期问题,一个简单的方法就是在web.xml中配置
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>