(一)easyUI之树形网络

  • 树形网格(TreeGrid)可以展示有限空间上带有多列和复杂数据电子表

    一、案例一:按tree的数据结构来生成

  • 前台
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<%
    String path = request.getContextPath();
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"
    href="<%=path%>/script/easyUI-1.4/themes/bootstrap/easyui.css">
<link rel="stylesheet" type="text/css"
    href="<%=path%>/script/easyUI-1.4/themes/icon.css">
<script type="text/javascript"
    src="<%=path%>/script/easyUI-1.4/jquery-1.8.3.min.js"></script>
<script type="text/javascript"
    src="<%=path%>/script/easyUI-1.4/jquery.easyui.min.js"></script>
<script type="text/javascript"
    src="<%=path%>/script/easyUI-1.4/locale/easyui-lang-zh_CN.js"></script>
</head>

<script type="text/javascript">
    jQuery(function(){
        $('#tt').treegrid({    
            url:"<%=path%>/servlet/treeGrid",    
            method: 'post',
            lines: true,
            rownumbers: true,
            //定义关键字段来标识树节点
            idField: 'dept_id',
            //treeField属性定义哪个字段显示为树形菜单
            treeField: 'dept_name',
            
            columns:[[    
                {title:'部门名称',field:'dept_name',width:180},    
                {title:'平均薪水',field:'salary',width:60,align:'right'},    
                {title:'部门地址',field:'address',width:80}  
            ]]    
        });  
    });
</script>

<body>
<h2>树形网格treeGrid</h2>
<table id="tt" style="width:600px;height:400px"></table>  
</body>
</html>
  • 后台
package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.google.gson.Gson;

import bean.Dept;
import util.DBUtil;

/**
 * Servlet implementation class DeptServlet
 */
@WebServlet("/servlet/treeGrid")
public class DeptServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        
        PrintWriter out=response.getWriter();
        String treeGrid_json="";
        String sql="";
        Connection conn=null;
        try {
            conn=DBUtil.getConn();
            QueryRunner queryRunner=new QueryRunner();
            sql="select * from dept";
            List<Map<String,Object>> treeGridData=new ArrayList<Map<String,Object>>();
            Map<String,Object> deptMap=null;
            List<Dept> deptList=queryRunner.query(conn,sql,new BeanListHandler<>(Dept.class));
            Map<String,Map<String,Object>> id_map=new HashMap<String,Map<String,Object>>();
            
            for(Dept dept:deptList){
                deptMap=new HashMap<String,Object>();
                
                deptMap.put("dept_id", dept.getDept_id());
                deptMap.put("dept_name", dept.getDept_name());
                deptMap.put("salary", dept.getSalary());
                deptMap.put("address", dept.getAddress());
                
                id_map.put(dept.getDept_id(), deptMap);
                
                if(dept.getGrade()>2){
                    deptMap.put("state", "closed");
                }
                
                if(dept.getParent_id().equals("0")){
                    //如果是父节点,则直接添加到treeGridData中
                    treeGridData.add(deptMap);
                    
                }else{
                    //如果是子节点
                    
                    Map<String,Object> parenMap=id_map.get(dept.getParent_id());
                    
                       if (parenMap != null) {
                            List<Map<String, Object>> children = null;

                            if (parenMap.get("children") == null) {
                                // 说明该父节点当前还没有一个子节点
                                children = new ArrayList<Map<String, Object>>();
                            } else {
                                children = (List<Map<String, Object>>) parenMap.get("children");
                            }
                            children.add(deptMap);
                            parenMap.put("children", children);

                        }
                }
                
            }
            Gson gson=new Gson();
            treeGrid_json=gson.toJson(treeGridData);
            
            out.println(treeGrid_json);
            out.flush();
            out.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }

}

结果:

  • 异步树请参考前几章。

 

 

 二、案例二:按Grid的数据结构来生成+查询功能

  •  数据库

  • 定义数据库函数:用于用于根据某个节点的所有父节点
BEGIN   
DECLARE fid varchar(100) default '';   
DECLARE str varchar(1000) default rootId;   
  
WHILE rootId is not null  do   
    SET fid =(SELECT parent_id FROM dept WHERE dept_id = rootId);   
    IF fid is not null THEN   
        SET str = concat(str, ',', fid);   
        SET rootId = fid;   
    ELSE   
        SET rootId = fid;   
    END IF;   
END WHILE;   
return str;  
END
  • 前台
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<%
    String path = request.getContextPath();
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"
    href="<%=path%>/script/easyUI-1.4/themes/bootstrap/easyui.css">
<link rel="stylesheet" type="text/css"
    href="<%=path%>/script/easyUI-1.4/themes/icon.css">
<script type="text/javascript"
    src="<%=path%>/script/easyUI-1.4/jquery-1.8.3.min.js"></script>
<script type="text/javascript"
    src="<%=path%>/script/easyUI-1.4/jquery.easyui.min.js"></script>
<script type="text/javascript"
    src="<%=path%>/script/easyUI-1.4/locale/easyui-lang-zh_CN.js"></script>
</head>

<script type="text/javascript">
    jQuery(function(){
        $('#tt').treegrid({    
            url:"<%=path%>/servlet/treeGrid",
            method : 'post',
            lines : true,
            rownumbers : true,
            //定义关键字段来标识树节点
            idField : 'dept_id',
            //treeField属性定义哪个字段显示为树形菜单
            treeField : 'dept_name',

            columns : [ [ {
                title : '部门名称',
                field : 'dept_name',
                width : 180
            }, {
                title : '平均薪水',
                field : 'salary',
                width : 60,
                align : 'right'
            }, {
                title : '部门地址',
                field : 'address',
                width : 80
            } ] ],
            toolbar: '#search_div'

        });
        
    });
    
    
    function doSearch(value,name){
        var paramData={
                 name:value
        };

        $('#tt').treegrid({ 
            queryParams:paramData
            
        });
        
    }
    
</script>

<body>
    <h2>树形网格treeGrid</h2>
    <div id="search_div">
        <input class="easyui-searchbox" style="width: 300px"
            data-options="searcher:doSearch,prompt:'Please Input Value'" name="keyWord"></input>
    </div>

    <table id="tt" style="width: 600px; height: 400px"></table>
</body>
</html>
  • 后台
package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import com.google.gson.Gson;

import util.DBUtil;

/**
 * Servlet implementation class DeptServlet
 */
@WebServlet("/servlet/treeGrid")
public class DeptServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        String sql = "";
        String keyWord = request.getParameter("name");

        if (keyWord == null  || keyWord.equals("")) {
            // 如果没有查询参数
            sql = "select * from dept";
        } else {
            /**
             * 如果游查询参数 1.先找出子菜单
             */
            String tempSQL = "select dept_id,dept_name from dept where dept_name like '%" + keyWord
                    + "%'  order by dept_id asc ";

            try {
                conn = DBUtil.getConn();
                QueryRunner queryRunner = new QueryRunner();
                List<Map<String, Object>> temList = queryRunner.query(conn, tempSQL, new MapListHandler());
                StringBuffer unionSQL = new StringBuffer();

                int rowIndex = 0;
                for (Map<String, Object> temMap : temList) {
                    String tem_dept_Id = String.valueOf(temMap.get("dept_id"));

                    /**
                     * 2.根据得到的tem_dept_Id,去寻找相应的子节点
                     * 请在数据库中定义一个函数,该函数用于根据某个节点的所有父节点
                     */
                    unionSQL.append(
                            "select dept_id from dept where FIND_IN_SET(dept_id,getParentList('" + tem_dept_Id + "'))");

                    rowIndex++;
                    if (rowIndex > 0 && rowIndex != temList.size()) {
                        unionSQL.append(" union ");
                    }

                }

                if (unionSQL.length() > 0) {
                    sql = "select * from dept where dept_id in(";
                    sql = sql + unionSQL.toString();
                    sql = sql + ")";
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        try {
            conn = DBUtil.getConn();

            stat = conn.createStatement();

            rs = stat.executeQuery(sql);
            List<Map<String, String>> gridDataList = new ArrayList<Map<String, String>>();
            Map<String, Object> gridDataMap = new HashMap<String, Object>();
            Map<String, String> columnMap = null;
            while (rs.next()) {

                String id = (String.valueOf(rs.getInt("dept_id")));
                String parent_id = (String.valueOf(rs.getInt("parent_id")));
                String dept_name = rs.getString("dept_name");
                String salary = rs.getString("salary");
                String address = rs.getString("address");

                columnMap = new HashMap<String, String>();
                columnMap.put("dept_id", id);
                columnMap.put("dept_name", dept_name);
                columnMap.put("salary", salary);
                columnMap.put("address", address);

                /**
                 * 加入树形表格的特殊属性,一定要加否则样式不成树状
                 */
                if (parent_id.equals("0") == false) {
                    columnMap.put("_parentId", parent_id);
                }

                gridDataList.add(columnMap);
            }
            gridDataMap.put("total", gridDataList.size());
            gridDataMap.put("rows", gridDataList);
            Gson gson = new Gson();
            String str_gridData = gson.toJson(gridDataMap);
            System.out.println(str_gridData);
            out.print(str_gridData);

        } catch (Exception e) {
            e.printStackTrace();
        }
        out.flush();
        out.close();

    }

}

结果:

 

posted @ 2017-10-24 17:12  shyroke、  阅读(2187)  评论(0编辑  收藏  举报
作者:shyroke 博客地址:http://www.cnblogs.com/shyroke/ 转载注明来源~