ztree asynchronous loading content --------- reissue Sunday

        On Saturday teacher demanded to be junior JAVA knowledge exchange, in general, is to give junior scoring seniors do something, then teach junior seniors if we build ztree. After all, the first contact ztree, so there are a lot of do not understand, but efforts by Saturday, or worked out. Now reissued.

  zTree rely on is a versatile "plug-tree" jQuery implementation. Excellent performance, flexible configuration, a combination of multiple functions is zTree biggest advantage. Want to know more can ztree website http://www.treejs.cn/v3/main.php#_zTreeInfo, today only talk about asynchronous loading.

  ztree three packets need to be introduced

<link rel="stylesheet" href="css/zTreeStyle/zTreeStyle.css" type="text/css">
    <script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="js/jquery.ztree.core.js"></script>

  You can go to the official website to download, and then introduced, (remember to modify the path !!!)

  Asynchronous load must be set in each attribute setting.async, because we want to contact the database, it must have a Servlet layer, a subject in need of course, the tree, the DBUtil layer connection to the database and the database operation layer Dao

  Ideas: the id and pid parent and child nodes linked to a parent id is the child's pid, it can be through the parent id, query so the pid is equal to the id to find his son, so the database can be set to id name pid.

  

 

 

 

首先通过页面向Servlet传来id(第一次传来的id是空,因为第一个没有父亲,所以传来的是空,但是我们得将他转换为0),然后通过父id来查找子节点。关键一步,因为子节点也可能是父节点,所以需要判断它是否为父亲节点,如果不是则isParent为false,(isParent在数对象里我把它默认成true);具体看代码

对象层

package Bin;

public class Tree {
    private int id;  
    private String name;
    private int pid;  // 父id
    private boolean IsParent = true;  // 是否为父节点
    private String url;    //跳转路径
    private String target;  //设置点击节点后在何处打开 url
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getPid() {
        return pid;
    }
    public void setPid(int pid) {
        this.pid = pid;
    }
    public boolean getIsParent() {
        return IsParent;
    }
    public void setIsParent(boolean isParent) {
        IsParent = isParent;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getTarget() {
        return target;
    }
    public void setTarget(String target) {
        this.target = target;
    }
    
}

Dao层

package Dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import Bin.Tree;
import Bin.Volunteer;
import DBUtil.Util;
public class Dao {
    /*
     * 查询
     */
    @Test
    public static List<Tree> query(int pid){
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Tree> list = new ArrayList<>();;
        try {
            // 获取连接
            con = Util.getConnection();
            // 编写sql语句
            String sql = "select * from City where pid = ?";
            // 执行sql语句
            ps = con.prepareStatement(sql);
            // 设置参数
            ps.setInt(1, pid);
            // 执行查询操作
            rs = ps.executeQuery();
            while(rs.next()) {
                 Tree city = new Tree();
                 city.setId(rs.getInt(1));
                 city.setName(rs.getString(2));
                 city.setPid(rs.getInt(3));    
                 list.add(city);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(rs!=null) {
                rs.close();
            }
            Util.release(con, ps);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
    // 查询某个节点是否有子节点
    public static int search(int id){
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int n = 0;
        try {
            // 获取连接
            con = Util.getConnection();
            // 编写sql语句
            String sql = "select * from City where pid = ?";
            // 执行sql语句
            ps = con.prepareStatement(sql);
            //设置参数
            ps.setInt(1, id);
            // 执行查询操作
            rs = ps.executeQuery();
            while(rs.next()) {
                n++;
            }        
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(rs!=null) {
                rs.close();
            }
            Util.release(con, ps);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return n;
    }    
}

DBUtil层:连接数据库和释放资源

package DBUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Util {
    // 获取连接
    // 获取连接方法
        public static Connection getConnection() {
            String driver = "com.mysql.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/tree?useSSL=false&useUnicode=true&characterEncoding=utf8";
            String username = "root";
            String password = "a3685371";
            Connection con = null;
            try {
                Class.forName(driver);
                con = DriverManager.getConnection(url,username,password);
            }catch(Exception e) {
                throw new RuntimeException(e);
            }
            return con;
        }
    // 释放资源
    
    public static void release(Connection con,PreparedStatement ps) {
        if(ps!=null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(con!=null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
}

Servlet层:

package Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Bin.Tree;
import Dao.Dao;
import net.sf.json.JSONArray;

/**
 * Servlet implementation class Servlet
 */
@WebServlet("/Servlet")
public class Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    Dao dao = new Dao();
    /**
     * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        String pid = request.getParameter("id");
        if(pid==null||pid.equals("")) {
            pid = 0+"";
        }
        List<Tree> list = Dao.query(Integer.parseInt(pid));
        for(int i=0;i<list.size();i++) {
            Tree tree = list.get(i);
            int n = Dao.search(tree.getId());
            if(n>=1) {
                tree.setIsParent(true);
                tree.setUrl("fenzhi.jsp");
                tree.setTarget("tree");
            }else {
                tree.setIsParent(false);
                tree.setUrl("yezi.jsp");
                tree.setTarget("tree");
            }
        }
        // 将list对象转换为json
        JSONArray  json  =  JSONArray.fromObject(list);
        // 将json对象转换为字符串
        String JSON = json.toString();
        // 将JSON相应给客户端
        PrintWriter pt = response.getWriter();
        pt.println(JSON);
    }    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
    
    <TITLE> ZTREE DEMO - Standard Data </TITLE>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="css/zTreeStyle/zTreeStyle.css" type="text/css">
    <script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="js/jquery.ztree.core.js"></script>
    <!--  <script type="text/javascript" src="../../../js/jquery.ztree.excheck.js"></script>
      <script type="text/javascript" src="../../../js/jquery.ztree.exedit.js"></script>-->
    <script type="text/javascript">
        var setting = {
                async: {
                    enable: true,  // 设置Ztree是否开启异步加载模式
                    url: "Servlet",        // 请求路径
                    autoParam:["id"]    // 异步加载时需要自动提交父节点属性的参数
                }
        };
        // 自动加载树
        $(document).ready(function(){
            $.fn.zTree.init($("#treeDemo"), setting);
        });
    </script>    
</HEAD>
<BODY style="background-color:#ff8888">
    <div class="zTreeDemoBackground left">
            <ul id="treeDemo" class="ztree"></ul>
    </div>
    
</BODY>
</HTML>

运行结果:

 

 当点击叶子节点时,跳转页面: 

 

 

 当点击父节点时,跳转页面: 

 

 

 

总结:树刚开始接触,不是很了解,还需多加练习。

 

如果有大佬发现错误或者有更简便的方法,请留言,感激不尽!!向您学习!!!!

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/yangxiao-/p/11986974.html