您的位置:首页 > 数据库

FastJson+Ztree:根据数据库层级表生成目录树

2013-03-30 09:36 309 查看
目标:
从数据库层级表:



到目录树结构的实现全过程:



中间产生的JSON数据:



实现途径:
配置jdbc数据源,从数据库中读取以上的层级表,将所有的记录存到ArrayList中,利用fastJson将其解析成JSON数据格式(序列化),而后利用ztree生成目录树结构。
工具版本:
fastJson1.1.9, ztree3.5, jdk1.7, struts1.2, jquery1.4, oracle9i
实现步骤:

index.jsp(访问http://localhost:8088/fastjson/index.jsp)
<%@ page language="java"import="java.util.*" pageEncoding="ISO-8859-1"%>

<%

String path = request.getContextPath();

String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>

<metahttp-equiv="pragma" content="no-cache">

<metahttp-equiv="cache-control" content="no-cache">

<metahttp-equiv="expires" content="0">

<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">

<metahttp-equiv="description" content="This is my page">

<!--

<linkrel="stylesheet" type="text/css"href="styles.css">

-->

</head>

<body>

<%

response.sendRedirect("getJson.do");

%>

</body>

</html>

GetJsonAction.java(ActionServlet)
package com.nns.struts.action;

importjavax.servlet.http.HttpServletRequest;

importcom.nns.util.Menu;

importcom.alibaba.fastjson.*;

importjava.util.ArrayList;

importjava.util.List;

importjavax.servlet.http.HttpServletResponse;

importorg.apache.struts.action.Action;

importorg.apache.struts.action.ActionForm;

importorg.apache.struts.action.ActionForward;

importorg.apache.struts.action.ActionMapping;

importjava.sql.Connection;

importjava.sql.ResultSet;

importjava.sql.SQLException;

importjava.sql.Statement;

importjavax.naming.Context;

importjavax.naming.InitialContext;

importjavax.naming.NamingException;

importjavax.sql.DataSource;

publicclass GetJsonAction extends Action {

publicActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequestrequest, HttpServletResponse response) {

List<Menu> m = new ArrayList<Menu>();

//连接数据源

Connectionconn = null;

try {

Context ctx= new InitialContext();

ContextcompNamingContext = (Context)ctx.lookup("java:comp/env");

DataSourceds = (DataSource)compNamingContext.lookup("jdbc/user1DataSource");

try {

conn =ds.getConnection();

if(conn==null){

System.out.println("获取数据源连接失败");

} else {

Statement st= conn.createStatement();

String sql ="select * from jsontree";

ResultSet rs= st.executeQuery(sql);

Stringid="",pid="",name="",t="";

while(rs.next()){

id=rs.getString("id");

pid=rs.getString("pid");

name=rs.getString("name");

t=rs.getString("t");

//System.out.println("=="+id+"=="+pid+"=="+name+"=="+t);

Menu m1 =new Menu();

m1.setId(id);

m1.setPid(pid);

m1.setName(name);

m1.setT(t);

m.add(m1);

}

}

} catch(SQLException e) {

e.printStackTrace();

}

} catch(NamingException e) {

e.printStackTrace();

} finally{

if(conn!=null){

try {

conn.close();

} catch(SQLException e) {

e.printStackTrace();

}

conn=null;

}

}

//序列化过程

String jsonString = JSON.toJSONString(m);

System.out.println("序列化(将javabean对象转换成json数据)");

System.out.println(jsonString.replaceAll("pid", "pId"));

request.setAttribute("jsondata", jsonString.replaceAll("pid", "pId"));

//反序列化测试

List<Menu> mcs = new ArrayList<Menu>();

mcs = JSON.parseArray(jsonString, Menu.class);

System.out.println("反序列化(将json数据还原成javabean对象)");

Iterator<Menu> iter = mcs.iterator();

while(iter.hasNext()){

Menu mu = iter.next();

System.out.println("id="+mu.getId()+";pid="+mu.getPid()+";name="+mu.getName()+";t="+mu.getT());

}

return mapping.findForward("success");

}

}

success.jsp(显示目录树页面):
<%@ page language="java"import="java.util.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

<title>My JSP 'goto.jsp' starting page</title>

<metahttp-equiv="pragma" content="no-cache">

<metahttp-equiv="cache-control" content="no-cache">

<metahttp-equiv="expires" content="0">

<metahttp-equiv="keywords" content="keyword1,keyword2,keyword3">

<metahttp-equiv="description" content="This is my page">

<scripttype="text/javascript" src="js/jquery-1.4.4.min.js"></script>

<script type="text/javascript"src="js/jquery.ztree.core-3.5.js"></script>

<script type="text/javascript" src="js/jquery.ztree.excheck-3.5.js"></script>

<linkrel="stylesheet" href="css/demo.css"type="text/css" />

<link rel="stylesheet"href="css/zTreeStyle/zTreeStyle.css" type="text/css" />

<SCRIPTtype="text/javascript">

var setting = {

data:{

key:{

title:"t"

},

simpleData:{

enable:true,

idKey:"id",

pIdKey:"pId",

rootPId:0

}

},

callback:{

onClick:onClick

}

};

var zNodes =<%=(String)request.getAttribute("jsondata")%>;

functionbeforeClick(treeId, treeNode, clickFlag) {

}

function onClick(event,treeId, treeNode, clickFlag) {

//treeId是目录树的id,即treeDemo

//alert('目录树的id:'+treeId);

//alert('名称:'+treeNode.name);

alert('父节点id:'+treeNode.pId);

alert('节点id:'+treeNode.id);

//alert('选中标示:'+clickFlag);

}

$(document).ready(function(){

$.fn.zTree.init($("#treeDemo"),setting, zNodes);

});

//-->

</SCRIPT>

</head>

<body>

<div>

<ul id="treeDemo" class="ztree">

</ul></div>

</body>

</html>

Menu.java(工具类javabean):
package com.nns.util;

import java.util.ArrayList;

import java.util.List;

public class Menu {

private String id = ""; //当前节点id

private String pid = ""; //父级节点 id

private String name = "";//节点名称

private String t=""; // 提示

//private List<Menu> menus = new ArrayList<Menu>();

//可根据需要添其他属性

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getPid() {

return pid;

}

public void setPid(String pid) {

this.pid = pid;

}

public String getT() {

return t;

}

public void setT(String t) {

this.t = t;

}

/*

public List<Menu> getMenus() {

return menus;

}

public void setMenus(List<Menu> menus) {

this.menus = menus;

}

*/

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: