树结构

 
 
 
 
@GetMapping("/tree")
	@ResponseBody
	public Tree<DeptDO> tree() {
		Tree<DeptDO> tree = new Tree<DeptDO>();
		tree = sysDeptService.getTree();
		return tree;
	}

控制层代码


@Override
	public Tree<DeptDO> getTree() {
		List<Tree<DeptDO>> trees = new ArrayList<Tree<DeptDO>>();
		List<DeptDO> SysDepts = sysDeptMapper.list(new HashMap<String,Object>());
		for (DeptDO SysDept : SysDepts) {
			Tree<DeptDO> tree = new Tree<DeptDO>();
			tree.setId(SysDept.getDeptNo().toString());
			tree.setParentId(SysDept.getParentNo().toString());
			tree.setText(SysDept.getDeptName());
			Map<String, Object> state = new HashMap<>();
			state.put("opened", true);
			tree.setState(state);
			trees.add(tree);
		}
		// 默认顶级菜单为0,根据数据库实际情况调整
		Tree<DeptDO> t = BuildTree.build(trees);
		return t;
	}
service层代码



package com.zsCat.common.base;

import com.alibaba.fastjson.JSON;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * tree TODO <br>
 * 
 * @author kangxu2 2017-1-7
 * 
 */
public class Tree<T> implements Serializable {
	/**
	 * 节点ID
	 */
	private String id;
	/**
	 * 显示节点文本
	 */
	private String text;
	/**
	 * 节点状态,open closed
	 */
	private Map<String, Object> state;
	/**
	 * 节点是否被选中 true false
	 */
	private boolean checked = false;
	/**
	 * 节点属性
	 */
	private Map<String, Object> attributes;

	/**
	 * 节点的子节点
	 */
	private List<Tree<T>> children = new ArrayList<Tree<T>>();

	/**
	 * 父ID
	 */
	private String parentId;
	/**
	 * 是否有父节点
	 */
	private boolean hasParent = false;
	/**
	 * 是否有子节点
	 */
	private boolean hasChildren = false;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public Map<String, Object> getState() {
		return state;
	}

	public void setState(Map<String, Object> state) {
		this.state = state;
	}

	public boolean isChecked() {
		return checked;
	}

	public void setChecked(boolean checked) {
		this.checked = checked;
	}

	public Map<String, Object> getAttributes() {
		return attributes;
	}

	public void setAttributes(Map<String, Object> attributes) {
		this.attributes = attributes;
	}

	public List<Tree<T>> getChildren() {
		return children;
	}

	public void setChildren(List<Tree<T>> children) {
		this.children = children;
	}

	public boolean isHasParent() {
		return hasParent;
	}

	public void setHasParent(boolean isParent) {
		this.hasParent = isParent;
	}

	public boolean isHasChildren() {
		return hasChildren;
	}

	public void setChildren(boolean isChildren) {
		this.hasChildren = isChildren;
	}

	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	public Tree(String id, String text, Map<String, Object> state, boolean checked, Map<String, Object> attributes,
                List<Tree<T>> children, boolean isParent, boolean isChildren, String parentID) {
		super();
		this.id = id;
		this.text = text;
		this.state = state;
		this.checked = checked;
		this.attributes = attributes;
		this.children = children;
		this.hasParent = isParent;
		this.hasChildren = isChildren;
		this.parentId = parentID;
	}

	public Tree() {
		super();
	}

	@Override
	public String toString() {

		return JSON.toJSONString(this);
	}

}

自定义树(封装返回的数据)

 
 
 
 

package com.zsCat.common.common.utils;


import com.zsCat.common.base.Tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BuildTree {

   public static <T> Tree<T> build(List<Tree<T>> nodes) {

      if (nodes == null) {
         return null;
      }
      List<Tree<T>> topNodes = new ArrayList<Tree<T>>();

      for (Tree<T> children : nodes) {

         String pid = children.getParentId();
         if (pid == null || "0".equals(pid)) {
            topNodes.add(children);

            continue;
         }

         for (Tree<T> parent : nodes) {
            String id = parent.getId();
            if (id != null && id.equals(pid)) {
               parent.getChildren().add(children);
               children.setHasParent(true);
               parent.setChildren(true);
               continue;
            }
         }

      }

      Tree<T> root = new Tree<T>();
      if (topNodes.size() == 1) {
         root = topNodes.get(0);
      } else {
         root.setId("0");
         root.setParentId("");
         root.setHasParent(false);
         root.setChildren(true);
         root.setChecked(true);
         root.setChildren(topNodes);
         root.setText("最外层文件夹");
         Map<String, Object> state = new HashMap<>();
         state.put("opened", true);
         root.setState(state);
      }

      return root;
   }

   public static <T> List<Tree<T>> buildList(List<Tree<T>> nodes, String idParam) {
      if (nodes == null) {
         return null;
      }
      List<Tree<T>> topNodes = new ArrayList<Tree<T>>();

      for (Tree<T> children : nodes) {

         String pid = children.getParentId();
         if (pid == null || idParam.equals(pid)) {
            topNodes.add(children);

            continue;
         }

         for (Tree<T> parent : nodes) {
            String id = parent.getId();
            if (id != null && id.equals(pid)) {
               parent.getChildren().add(children);
               children.setHasParent(true);
               parent.setChildren(true);

               continue;
            }
         }

      }
      return topNodes;
   }

}

工具类操作数据到树中



create table
CREATE TABLE `sys_dept` (
   `dept_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
   `dept_no` varchar(50) DEFAULT NULL COMMENT '机构编码',
   `parent_no` varchar(50) DEFAULT NULL COMMENT '父机构编码',
   `dept_name` varchar(255) DEFAULT NULL COMMENT '机构名称',
   `sort` int(11) DEFAULT NULL COMMENT '排序',
   `type` varchar(50) DEFAULT NULL COMMENT '机构类型',
   `isUse` tinyint(4) DEFAULT NULL COMMENT '是否启用  1:启用,0:停用',
   `isEngineering` tinyint(4) DEFAULT NULL COMMENT '是否为工程部0不是1是',
   `pattern` varchar(50) DEFAULT NULL COMMENT '模式、在isEngineering基础上会有',
   `remarks` varchar(255) DEFAULT NULL COMMENT '备注',
   `del_flag` tinyint(4) DEFAULT '0' COMMENT '是否删除  -1:已删除  0:正常',
   `create_by` varchar(50) DEFAULT NULL COMMENT '创建人',
   `create_date` datetime DEFAULT NULL COMMENT '创建时间',
   `update_by` varchar(50) DEFAULT NULL COMMENT '修改人',
   `update_date` datetime DEFAULT NULL COMMENT '修改时间',
   `rank` int(11) DEFAULT NULL COMMENT '级别',
   PRIMARY KEY (`dept_id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8 COMMENT='部门管理'
<select id="list" resultType="com.zscat.shop.domain.DeptDO">
		select `dept_id`,`dept_no`,`parent_no`,`dept_name`,`sort`,`type`,`isUse`,`isEngineering`,`pattern`,`remarks`,`del_flag`,`create_by`,`create_date`,`update_by`,`update_date`,`rank` from sys_dept
		<where>
			<if test="deptId != null and deptId != ''"> and dept_id = #{deptId} </if>
			<if test="deptNo != null and deptNo != ''"> and dept_no = #{deptNo} </if>
			<if test="parentNo != null and parentNo != ''"> and parent_no = #{parentNo} </if>
			<if test="deptName != null and deptName != ''"> and dept_name = #{deptName} </if>
			<if test="sort != null and sort != ''"> and sort = #{sort} </if>
			<if test="type != null and type != ''"> and type = #{type} </if>
			<if test="isuse != null and isuse != ''"> and isUse = #{isuse} </if>
			<if test="isengineering != null and isengineering != ''"> and isEngineering = #{isengineering} </if>
			<if test="pattern != null and pattern != ''"> and pattern = #{pattern} </if>
			<if test="remarks != null and remarks != ''"> and remarks = #{remarks} </if>
			<if test="delFlag != null and delFlag != ''"> and del_flag = #{delFlag} </if>
			<if test="createBy != null and createBy != ''"> and create_by = #{createBy} </if>
			<if test="createDate != null and createDate != ''"> and create_date = #{createDate} </if>
			<if test="updateBy != null and updateBy != ''"> and update_by = #{updateBy} </if>
			<if test="updateDate != null and updateDate != ''"> and update_date = #{updateDate} </if>
			<if test="rank != null and rank != ''"> and rank = #{rank} </if>
		</where>
		<choose>
			<when test="sort != null and sort.trim() != ''">
				order by ${sort} ${order}
			</when>
			<otherwise>
				order by dept_id desc
			</otherwise>
		</choose>
		<if test="offset != null and limit != null">
			limit #{offset}, #{limit}
		</if>
	</select>

数据库结构  建表语句   和查询语句




页面和js

<link href="/css/plugins/jsTree/style.min.css" rel="stylesheet">
<link href="/css/plugins/jqTreeGrid/jquery.treegrid.css" rel="stylesheet">
<link href="/css/plugins/bootstrap-table/bootstrap-table.min.css"
   th:href="@{/css/plugins/bootstrap-table/bootstrap-table.min.css}"
   rel="stylesheet">

<script src="/js/plugins/jsTree/jstree.min.js"></script>
<script src="/js/plugins/jqTreeGrid/jquery.treegrid.min.js"></script>
<script src="/js/plugins/jqTreeGrid/jquery.treegrid.extension.js"></script>
<script src="/js/plugins/jqTreeGrid/jquery.treegrid.bootstrap3.js"></script>
<script src="/js/jquery.min.js?v=2.1.4"></script>
<script src="/js/bootstrap.min.js?v=3.3.6"></script>

<body class="gray-bg">
	<div class="wrapper wrapper-content ">
		<div class="row">
			<div class="col-sm-3">
				<div class="ibox ibox-body">
					<div class="ibox-title">
						<h5>全部分类</h5>
					</div>
					<div class="ibox-content">
						<div id="jstree"></div>
					</div>
				</div>
			</div>
		</div>
	</div>
var prefix = "/ERP/commodity"     //请求前缀
$(function() {
	getTreeData();
	load();
});
//从后台获取树数据
function getTreeData() {
	$.ajax({
		type : "GET",
		url : "/system/sysDept/tree",
		success : function(tree) {
			loadTree(tree);
		}
	});
}
//加载数据
function loadTree(tree) {
$('#jstree').jstree("destroy");    //销毁树,从新加载
	$('#jstree').jstree({
'core' : {'data' : tree},"plugins" : [ "search" ]});$('#jstree').jstree().open_all();}
$('#jstree').on("changed.jstree", function(e, data) {       //方法1



	if (data.selected == 0) {
		var opt = {
			query : {
                deptNo : '',
			}
		}
		$('#exampleTable').bootstrapTable('refresh', opt);
	} else {
		var opt = {
			query : {
                deptNo : data.selected[0],
			}
		}
		$('#exampleTable').bootstrapTable('refresh',opt);
	}

});


$('#jstree').on("changed.jstree", function(e, data) {   //方法2
  parent.loadPosition(data.selected);
    var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
    parent.layer.close(index);
});

给树结构添加的选择事件


猜你喜欢

转载自blog.csdn.net/qq_40680190/article/details/80360693