JSP树形菜单的实现(转载)
(2009-04-20 15:21:03)
转载
标签:
杂谈 分类:技术讲解
1。原理简介
dtree是一个免费的javascript脚本,只需定义有限的几个参数,就可以做出漂亮的树型菜单。下载目录:www.destroydrop/javascripts/tree/
以下是dtree的用法示例:
1)初始化菜单
<script type="text/javascript">
<!--
var Tree = new Array;
// nodeId | parentNodeId | nodeName | nodeUrl
Tree[0]  = "1|0|Page 1|#";
Tree[1]  = "2|1|Page 1.1|#";
Tree[2]  = "3|1|Page 1.2|#";
Tree[3]  = "4|3|Page 1.2.1|#";
Tree[4]  = "5|1|Page 1.3|#";
Tree[5]  = "6|2|Page 1.1.1|#";
Tree[6]  = "7|6|Page 1.1.1.1|#";
Tree[7]  = "8|6|Page 1.1.1.2|#";
Tree[8]  = "9|1|Page 1.4|#";
Tree[9]  = "10|9|Page 1.4.1|#";
Tree[10] = "11|0|Page 2|#";
//-->
</script>
2)调用函数
<div class="tree">
<script type="text/javascript">
<!--
createTree(Tree,1,7);  // starts the tree at the top and open it at node nr. 7
//-->
</script>
</div>
显然,如果用动态的脚本来初始化菜单数组(asp,jsp均可),那就可以很方便的实现动态的树型菜单了。
2。jsp动态实现
分以下步骤实现动态的树型菜单:
1)在数据库建tree_info表,有nodeId,parentNodeId,nodeName,nodeUrl四个字段,来存储节点信息。
2)编写java类,用于从数据库出节点信息,并且生成javascript脚本。
3)编写tag类。用于封装逻辑,简化jsp的开发。
4)建一个web程序进行测试。
3。详细过程
1)在数据库建表,脚本如下:
CREATE TABLE `test`.`tree_info` (
`node_id` INTEGER UNSIGNED NOT NULL DEFAULT -1,
`parent_id` INTEGER UNSIGNED NOT NULL DEFAULT -1,
`node_name` VARCHAR(45) NOT NULL,
`ref_url` VARCHAR(45) NOT NULL,
PRIMARY KEY(`node_id`)
)
我使用mysql数据库,如果脚本细节有出入,请自行修改
按照上面的dTree示例插入数据
2)编写TreeInfo.java,这个类用于封装节点信息
package com.;
public class TreeInfo {
private int nodeId = -1;//node id
private int parentId = -1;//parentId
private String nodeName = null;//node name
private String url = null;//url references
public int getNodeId() {
return nodeId;
}
public void setNodeId(int nodeId) {
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
编写TreeUtil.java,用于从数据库得到节点信息,封装到TreeInfo对象,并生成javascript
脚本
TreeUtil.java
package com.;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.DriverManager;
public class TreeUtil {
public static List retrieveNodeInfos(){
List coll = new ArrayList();
String driverName = "sql.jdbc.Driver";
String host = "localhost";
String port = ":3306";
String serverID = "test";
String userName = "root";
String userPwd = "root";
String url = "jdbc:mysql://" + host + port + "/" + serverID ;
Connection conn = null ;
PreparedStatement ps = null;
ResultSet rs = null;
try{
Class.forName(driverName).newInstance();
conn = Connection(url , userName , userPwd);
String sql = "select * from tree_info";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
TreeInfo info = null;
while(rs!=null && rs.next()){
info = new TreeInfo();
info.Int(1));
info.Int(2));
info.String(3));
info.String(4));
coll.add(info);
}
//            if(rs!=null){
//                rs.close();
//                rs=null;
//            }
//            if(ps!=null){
//                ps.close();
//                ps=null;
/
/            }
}catch(Exception e){
System.out.println(e);
}
return coll;
}
public static String createTreeInfo(List alist){
StringBuffer contents = new StringBuffer();
contents.append("<!--\n");
contents.append("var Tree = new Array;");//create a array in javascript
TreeInfo info =null;
for(int max = alist.size(),i=0;i<max;i++){
info = ((i);
//define elements of array
contents.append("Tree[");
contents.append(i);
contents.append("]=\"");
contents.NodeId());
contents.append("|");
contents.ParentId());
contents.append("|");
contents.NodeName());
contents.append("|");
contents.Url());
contents.append("\";");
}
contents.append("docment.writer(Tree);");
contents.append("//-->");
String();
}
public static void main(String[]args){
List alist = ieveNodeInfos();
//        TreeInfo info = null;
/
/        for(Iterator i = c.iterator();i.hasNext();){
//            info = (();
//            System.out.println("*****" + NodeName());
//        }
System.out.ateTreeInfo(alist));
}
}
3)编写标签类
InitTreeTag.java
package com.diegoyun.web.taglibs;
import com.TreeUtil;
import javax.servlet.jsp.tagext
.TagSupport;
import javax.servlet.jsp.JspException;
import java.io.IOException;
public class InitTreeTag extends TagSupport{
public int doEndTag() throws JspException {
StringBuffer tree = new StringBuffer();
tree.append("<script type=\"text/javascript\">\n");
tree.ieveNodeInfos()));
tree.append("</script>\n");
try{
}catch(IOException ioe){
ioe.printStackTrace();
}
return super.doEndTag();
}
}
ShowTreeTag.java :
package com.diegoyun.web.taglibs;
import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.JspException;
import java.io.IOException;
public class ShowTreeTag extends TagSupport{
public int doEndTag() throws JspException {
StringBuffer buffer = showTree();
try {
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return super.doEndTag();
}
private StringBuffer showTree(){
StringBuffer sb = new StringBuffer();
sb.append("<div class=\"tree\">\n");
sb.append("<script type=\"text/javascript\">\n");
sb.append("<!--\n");
sb.append("createTree(Tree);\n");
sb.append("//-->\n");
sb.append("</script>\n");
sb.append("</div>\n");
return sb;
}
标签的tld如下:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"java.sun/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>tree</short-name>
<!--initTreeTag-->
<tag>
<name>init</name>
<tag-class>com.diegoyun.web.taglibs.InitTreeTag</tag-class>
<body-content>empty</body-content>
</tag>
<!--ShowTreeTag-->
<tag>
<name>show</name>
<tag-class>com.diegoyun.web.taglibs.ShowTreeTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
4)建立web过程,编写jsp进行测试。
index.jsp如下:
<%@ page language="java"%>
<%@ taglib uri="/WEB-INF/tlds/tree.tld" prefix="tree"%>
<html>
<head>
<title>Tree example</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="StyleSheet" href="tree.css" type="text/css">
<script type="text/javascript" src="tree.js"></script>
<tree:init/>
</head>
<body>
<b>Tree example :</b><br /><br />
<tree:show/>
<br /><br />
</body>
</html>
测试,enjoy yourself!
5)修改过的JS文件
function TreeSelector(item, data, rootId) {
this._data = data;//下拉列表菜单的数组
this._item = item;//下拉列表菜单对像
this._rootId = rootId;//创建菜单的根结点
this._sel=0;
}
//创建菜单不带默认选项
ateTree = function() {
var len = this._data.length;
var temp = 0;
for
( var i = 0; i < len; i++) {
//if (this._data[i].pid=='9'){temp = i;}
if (this._data[i].pid == this._rootId) {
this._item.options.add(new Option(".." + this._data[i].text,
this._data[i].id));
for ( var j = 0; j < len; j++) {
}
}
}
};
ateSubOption = function(len, current, next) {
var blank = "..";
if (next.pid == current.id) {
intLevel = 0;
var intlvl = Level(this._data, this._rootId, current);
for (a = 0; a < intlvl; a++)
blank += "..";
blank += "├-";
this._item.options.add(new Option(blank + , next.id));
for ( var j = 0; j < len; j++) {
}
}
};
Level = function(datasources, topId, currentitem) {
var pid = currentitem.pid;
if (pid != topId) {
for ( var i = 0; i < datasources.length; i++) {
if (datasources[i].id == pid) {
intLevel++;
}
}
}
return intLevel;
};
//根据需要选择菜单值创建对应下拉菜单选择
function SelTreeSelector(item, data, rootId,did) {
this._data = data;//下拉列表菜单的数组
this._item = item;//下拉列表菜单对像
this._rootId = rootId;//创建菜单的根结点
this._sel=0;
this._did=did;//缺省的选择菜单值
}
//创建下拉菜单带默认选项主要用于修改状态
ateTree = function() {
var len = this._data.length;
var temp = 0;
for ( var i = 0; i < len; i++) {
if (this._data[i].pid == this._rootId) {
this._item.options.add(new Option(".." + this._data[i].text,
this._data[i].id));
for ( var j = 0; j < len; j++) {
}
}
}
for ( var i=0;i<len;i++){
if(this._item.options[i].value==this._did){this._sel=i;}
}
this._item.options.selectedIndex=this._sel;
};
ateSubOption = function(len, current, next) {
var blank = "..";
if (next.pid == current.id) {
intLevel = 0;
var intlvl = Level(this._data, this._rootId, current);
for (a = 0; a < intlvl; a++)
blank += "..";
blank += "├-";
this._item.options.add(new Option(blank + , next.id));
for ( var j = 0; j < len; j++) {
}
}
};
nodeselector
Level = function(datasources, topId, currentitem) {
var pid = currentitem.pid;
if (pid != topId) {
for ( var i = 0; i < datasources.length; i++) {
if (datasources[i].id == pid) {
intLevel++;
}
}
}
return intLevel;
};

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。