ztree+dwr实现异步加载树形菜单

ztree的相关文件可以去官网http://baby666.cn/hunter/zTree.html下载,dwr的jar包自己下,直接贴代码如下:

1.index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <HTML> <HEAD> <link rel="stylesheet" href="./css/demo.css" mce_href="css/demo.css" type="text/css"> <link rel="stylesheet" href="./css/zTreeStyle.css" mce_href="css/zTreeStyle.css" type="text/css"> <mce:script type="text/javascript" src="./js/jquery-1.4.2.js" mce_src="js/jquery-1.4.2.js"></mce:script> <mce:script type="text/javascript" src="./js/jquery-ztree-2.5.js" mce_src="js/jquery-ztree-2.5.js"></mce:script> <mce:script type="text/javascript" src="<%=path%><!-- /dwr/interface/utilCommon.js"> // --></mce:script> <mce:script type="text/javascript" src="<%=path%><!-- /dwr/engine.js"> // --></mce:script> <mce:script type="text/javascript" src="<%=path%><!-- /dwr/util.js"> // --></mce:script> <mce:script type="text/javascript" src="./js/demoTools.js" mce_src="js/demoTools.js"></mce:script> <SCRIPT LANGUAGE="JavaScript"> <!-- var zTree1; var setting; var isGetNodes = false; var zNodes =[ {name:"中国", id:"1", isParent:true} ]; setting = { expandSpeed: "", callback: { beforeExpand: zTreeBeforeExpand, beforeCollapse: zTreeBeforeCollapse, expand: zTreeOnExpand, collapse: zTreeOnCollapse } }; $(document).ready(function(){ zTree1 = $("#treeDemo").zTree(setting, clone(zNodes, "")); }); var isGetNodes = false; var curParentNode = null; function zTreeBeforeExpand(treeId, treeNode) { if (!isGetNodes && treeNode.isParent && (!treeNode.nodes || treeNode.nodes.length==0)) { curParentNode = treeNode; isGetNodes = true; var id = curParentNode.id; utilCommon.get(id,function(msg){ if (!msg || msg.length == 0) { isGetNodes = false; return; } var newNodes = ""; try { newNodes = eval("(" + msg + ")"); } catch(err) {} if (newNodes && newNodes != "") { zTree1.addNodes(curParentNode, newNodes, true); zTree1.updateNode(curParentNode); zTree1.selectNode(curParentNode.nodes[0]); isGetNodes = false; } }); return false; } return true; } function zTreeOnExpand(event, treeId, treeNode) { } function zTreeBeforeCollapse(treeId, treeNode) { } function zTreeOnCollapse(event, treeId, treeNode) { } //--> </SCRIPT> </HEAD> <BODY> <TABLE border=0 width="700" class="tb1"> <TR> <TD width=340px align=center valign=top> <div class="zTreeDemoBackground"> <ul id="treeDemo" class="tree"></ul> </div> </TD> </TR> </TABLE> </BODY> </HTML>

 

 

2.TreeNode.java

package util; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Vector; public class TreeNode { private int id; private String name; private int parentId; private String parentName; private boolean isHasChild; public TreeNode() { } public TreeNode(int id) { this.id = id; if (!init()) { this.id = -1; } } // 初始化节点 public boolean init() { String sql = "select * from treenode where id=" + getId(); Connection conn = null; Statement st = null; ResultSet rs = null; boolean flag = false; try { conn = DBUtil.getConnection(); st = conn.createStatement(); rs = st.executeQuery(sql); if (rs.next()) { this.parentId = rs.getInt("parentid"); this.name = rs.getString("name"); this.parentName = rs.getString("parentname"); this.isHasChild = canExpand(); flag = true; } rs.close(); st.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); return false; } return flag; } // 是否可以展开 public boolean canExpand() { boolean flag = false; String sql = "select * from treenode where parentid=" + getId(); Connection conn = null; Statement st = null; ResultSet rs = null; try { conn = DBUtil.getConnection(); st = conn.createStatement(); rs = st.executeQuery(sql); if (rs.next()) { flag = true; } rs.close(); st.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } return flag; } // 取得子节点列表 public List<TreeNode> getChildren() { String sql = "select * from treenode where parentid=" + getId(); Connection conn = null; Statement st = null; ResultSet rs = null; List<TreeNode> children = new ArrayList<TreeNode>(); try { conn = DBUtil.getConnection(); st = conn.createStatement(); rs = st.executeQuery(sql); while (rs.next()) { TreeNode t = new TreeNode(); t.setId(rs.getInt("id")); t.setIsHasChild(t.canExpand()); t.setName(rs.getString("name")); t.setParentId(rs.getInt("parentid")); t.setParentName(rs.getString("parentname")); children.add(t); } rs.close(); st.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); return null; } return children; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getParentId() { return parentId; } public void setParentId(int parentId) { this.parentId = parentId; } public String getParentName() { return parentName; } public void setParentName(String parentName) { this.parentName = parentName; } public void setId(int id) { this.id = id; } public int getId() { return id; } public void setIsHasChild(boolean isHasChild) { this.isHasChild = isHasChild; } public boolean getIsHasChild() { return isHasChild; } }

3.DBUtil.java

package util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBUtil { //取得数据库连接 public static Connection getConnection() { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("驱动程序没有找到" + e.getMessage()); } try { conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/tree", "root", "123"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("获得连接出错!"); } return conn; } }

4.UtilCommon.java

package util; import java.util.List; public class UtilCommon { public static String get(String id) { String s = ""; TreeNode node = new TreeNode(Integer.parseInt(id)); if (node.getIsHasChild()) { List<TreeNode> children = node.getChildren(); s="["; for (TreeNode t : children) { s+="{id:'"+t.getId()+"',name:'"+t.getName()+"',isParent:"+t.getIsHasChild()+"},"; } s=s.substring(0,s.length()-1); s+="]"; } return s; } public static void main(String[] args) { System.out.println(get("1")); } }

5.web.xml

<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>dwr</servlet-name> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> <!--此处指定项目处于开发之中,故可通过http://localhost:8000/dwrdemo1/dwr/,而不会出现403 --> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>crossDomainSessionSecurity</param-name> <param-value>false</param-value> </init-param> <!-- dwr产生failed to read input的解决方法 --> <init-param> <param-name>classes</param-name> <param-value>java.lang.Object</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dwr</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping> </web-app>

6.dwr.xml

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN" "http://www.getahead.ltd.uk/dwr/dwr10.dtd"> <dwr> <!-- without allow, DWR isn't allowed to do anything --> <allow> <create creator="new" javascript="utilCommon"> <param name="class" value="util.UtilCommon"/> </create> </allow> </dwr>

7.sql脚本

/* SQLyog 企业版 - MySQL GUI v8.14 MySQL - 5.6.2-m5 : Database - tree ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`tree` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `tree`; /*Table structure for table `treenode` */ DROP TABLE IF EXISTS `treenode`; CREATE TABLE `treenode` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(10) DEFAULT NULL, `parentid` int(11) DEFAULT NULL, `parentName` varchar(10) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; /*Data for the table `treenode` */ insert into `treenode`(`id`,`name`,`parentid`,`parentName`) values (1,'中国',0,NULL),(2,'江苏',1,'中国'),(3,'北京',1,'中国'),(4,'南京',2,'四川'),(5,'朝阳区 ',3,'北京'); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

 

运行效果:

 

源码可以去http://download.csdn.net/source/3389285下载

你可能感兴趣的:(sql,String,function,DWR,Class,stylesheet)