java实现Ztree的增删改查(包含后台代码)

1、前端页面

<body>
    <div class=" page-content clearfix">
      <div class="t_Record" style="width:90%">
        <div class="tree-ads" id="tree-ads">
          <div id="tree-sorts" class="ztree"></div>
        </div>
      </div>
    </div>
  </body>

2、js代码以及配置项

$(function() {
    onLoadZTree();
  })
  /*******树状图*******/
  var setting = {
    view: {
      dblClickExpand: false,
      showLine: false,
      selectedMulti: false,
      addHoverDom: addHoverDom, //显示按钮
      removeHoverDom: removeHoverDom, //隐藏按钮
    },
    edit: {
      enable: true,
      editNameSelectAll: true,
      removeTitle: '删除',
      renameTitle: '重命名'
    },
    data: {
      simpleData: {
        enable: true,
        idKey: "id",
        pIdKey: "pId",
        rootPId: "0"
      }
    },
    callback: {
      beforeRemove: beforeRemove, //点击删除时触发,用来提示用户是否确定删除
      beforeEditName: beforeEditName, //点击编辑时触发,用来判断该节点是否能编辑,是否进入编辑状态
      beforeRename: beforeRename, //编辑结束时触发,用来验证输入的数据是否符合要求
    }
  };

  function onLoadZTree() {
    $.ajax({
      async: false, //是否异步
      cache: false, //是否使用缓存
      type: 'POST', //请求方式:post
      url: 'ads/cat/list', //请求的路径
      success: function(data) {
        treeNodes = data; //把后台封装好的简单Json格式赋给treeNodes
      }
    });
    var t = $("#tree-sorts");
    t = $.fn.zTree.init(t, setting, treeNodes);
    t.expandAll(true);
  }
  //新增
  function addHoverDom(treeId, treeNode) {
    var sObj = $("#" + treeNode.tId + "_span");
    if(treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId +
      "' title='新增' onfocus='this.blur();'></span>";
    sObj.after(addStr);
    var btn = $("#addBtn_" + treeNode.tId);
    if(btn) btn.bind("click", function() {
      var zTree = $.fn.zTree.getZTreeObj("tree-sorts");
      layer.prompt({
        formType: 0,
        value: '',
        title: '请输入节点名称'
      }, function(value, index) {
        if(value.trim().length === 0) {//非空验证
          return false;
        }
        layer.close(index)
        var pid = treeNode.id;
        var name = value;
        $.ajax({
          type: "POST",
          async: false,
          url: "ads/sort/add",
          data: {
            "pid": pid,
            "name": name
          },
          success: function(data) {
            if(data.status == 200) {
              zTree.addNodes(treeNode, {
                pId: treeNode.id,
                name: value
              });
              onLoadZTree() //重新加载,不然再次添加会报错
              layer.msg('添加成功', {
                icon: 1,
                time: 1000
              });
            } else {
              onLoadZTree()
              layer.msg('' + data.msg + '', {
                icon: 5,
                time: 1000
              });
            }
          }
        });
      });

    });
  };
  //移除鼠标隐藏按钮
  function removeHoverDom(treeId, treeNode) {
    $("#addBtn_" + treeNode.tId).unbind().remove();
  }
  /*
   * 编辑
   */
  function beforeEditName(treeId, treeNode) {
    return true;
  }

  function beforeRename(treeId, treeNode, newName, isCancel) {
    if(newName.trim().length === 0) {
      layer.msg('名称不能为空', {
        icon: 5,
        time: 1000
      })
      return false;
    } else {
      $.ajax({
        type: "POST",
        async: false,
        url: "ads/sort/update",
        data: {
          "id": treeNode.id,
          "name": newName
        },
        success: function(data) {
          if(data.status == 200) {
            onLoadZTree() //重新加载,不然再次添加会报错
            layer.msg('修改成功', {
              icon: 1,
              time: 1000
            });
            return true;
          } else {
            onLoadZTree()
            layer.msg('' + data.msg + '', {
              icon: 5,
              time: 1000
            });
            return false;
          }
        }
      });
    }
  }

  /*
   * 删除
   */
  function beforeRemove(treeId, treeNode) {
    if(treeNode.isParent == true) {
      layer.msg('请首先删除子节点', {
        icon: 5,
        time: 1000
      });
      return false;
    }
    layer.confirm('确认要删除吗?', {
        btn: ['确定', '取消']
      }, function(index) {
        $.ajax({
          type: "POST",
          async: false,
          url: "ads/sort/delete",
          data: {
            "id": treeNode.id,
            "pId": treeNode.pId
          },
          success: function(data) {
            if(data.status == 200) {
              onLoadZTree() //重新加载,不然再次添加会报错
              layer.msg('删除成功', {
                icon: 1,
                time: 1000
              });
              return true;
            } else {
              onLoadZTree()
              layer.msg('' + data.msg + '', {
                icon: 5,
                time: 1000
              });
              return false;
            }
          }
        });
        layer.close(index);
      },
      function() {//取消时刷新tree
        onLoadZTree()
        layer.msg('已取消', {
          icon: 6,
          time: 1000
        });
        return false;
      }
    );
  }

注意:在前端页面中,ztree默认的css中没有新增按钮,需要在样式文件添加如下一句样式

.ztree li span.button.add {margin-right:2px; background-position:-143px 0px; vertical-align:top; *vertical-align:middle}

3、后台代码,主要就是增加和删除,其他的不写

//增加
public Result addTbcontentCategory(long pid, String name) throws Exception {
		TbContentCategory category=new TbContentCategory();
		category.setParentId(pid);
		category.setName(name);
		category.setStatus(1);
		category.setIsParent(false);
		category.setSortOrder(getOrder(pid));
		Date date=new Date();
		category.setCreated(date);
		category.setUpdated(date);
		categoryMapper.insert(category);
		//查看是否为父结点
		TbContentCategory contentCategory = categoryMapper.selectByPrimaryKey(pid);
		//不是父节点修改为父结点
		if(!contentCategory.getIsParent()){
			contentCategory.setIsParent(true);
			categoryMapper.updateByPrimaryKey(contentCategory);
		}
		return Result.ok();
	}
	//排序
	private int getOrder(long pid) {
		TbContentCategory category = categoryMapper.selectByPrimaryKey(pid);
		if(category==null) {
			return 1;
		}else {
			TbContentCategoryExample example=new TbContentCategoryExample();
			TbContentCategoryExample.Criteria criteria = example.createCriteria();
			criteria.andParentIdEqualTo(pid);
			List<TbContentCategory> cat = categoryMapper.selectByExample(example);
			if(cat.size()<=0||cat==null) {
				return 1;
			}else {
				return cat.size()+1;
			}			
		}
	}

//删除
public Result deleteTbcontentCategory(long id,long pId) throws Exception {
		TbContentCategory category = categoryMapper.selectByPrimaryKey(pId);
		categoryMapper.deleteByPrimaryKey(id);
		if(category.getIsParent()){//如果是父类目,改成非父类目
			category.setIsParent(false);
			categoryMapper.updateByPrimaryKey(category);
		}
		return Result.ok();
	}
	

有不对的地方,还希望大神指正,3Q

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

熟透的蜗牛

永远满怀热爱,永远热泪盈眶

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值