Ztree整合SpringMVC实现异步加载树

2022-08-09 15:10:22 浏览数 (2)

正值清明时节,天气也将开始升温了,夏天即将到来,你做好准备了吗?好了,废话少扯,切入正题,本文笔者将要讲解的是JQuery的树插件Ztree。现在web项目基本上也都是使用Ztree作为树组件进行实现的。 好了,来看下最终实现的效果图:

笔者这里使用的是Mysql数据库,先创建一张表。

代码语言:javascript复制
CREATE TABLE `city_ztree` (              
              `id` varchar(36) NOT NULL,             
              `city_name` varchar(50) DEFAULT NULL,  
              `parent_id` varchar(36) DEFAULT NULL,  
              PRIMARY KEY (`id`)                     
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8

而后插入些测试数据。

代码语言:javascript复制
insert into `city_ztree`(`id`,`city_name`,`parent_id`) values ( '1a','福建省','0');
 insert into `city_ztree`(`id`,`city_name`,`parent_id`) values ( '2b','浙江省','0');  
 insert into `city_ztree`(`id`,`city_name`,`parent_id`) values ( '3c','广东省','0');
 insert into `city_ztree`(`id`,`city_name`,`parent_id`) values ( '4d','江苏省','0');
insert into `city_ztree`(`id`,`city_name`,`parent_id`) values ( '1a1','福州市','1a');
 insert into `city_ztree`(`id`,`city_name`,`parent_id`) values ( '1a2','厦门市','1a');
 insert into `city_ztree`(`id`,`city_name`,`parent_id`) values ( '1a3','泉州市','1a');
 insert into `city_ztree`(`id`,`city_name`,`parent_id`) values ( '1a4','漳州市','1a');
 insert into `city_ztree`(`id`,`city_name`,`parent_id`) values ( '1a5','莆田市','1a');
 insert into `city_ztree`(`id`,`city_name`,`parent_id`) values ( '1a6','宁德市','1a');
 insert into `city_ztree`(`id`,`city_name`,`parent_id`) values ( '1a7','三明市','1a');
 insert into `city_ztree`(`id`,`city_name`,`parent_id`) values ( '1a8','南平市','1a');
 insert into `city_ztree`(`id`,`city_name`,`parent_id`) values ( '1a9','龙岩市','1a');

由于篇幅原因,只截取部分数据,自己想要更多数据,可自行插入,只要id和parent_id保持上下级关系就好了。而后在创建一个与表对应的javabean实体类。

代码语言:javascript复制
public class CityZtree {

    private String id;
    private String cityName;
    private String parentId;
    //由于篇幅原因,在此省略get/set方法
    }

表有了,测试数据也有了,与表对应的实体类也创建了,那现在就可以操作Dao了,来建一个Dao接口。

代码语言:javascript复制
import com.zhenqi.entity.CityZtree;

import java.util.List;

/**
 * Created by wuming on 2019/4/5.
 */
public interface CityZtreeDao {

    /**
     * 根据父id查找树
     * @param parentId
     * @return
     */
    public List<CityZtree> findCityZtreeByParentId(String parentId);

    /**
     * 当前节点是否还有子节点
     * @param id
     * @return
     */
    public Integer hasChild(String id);
}

笔者使用的是Mybatis作为ORM,故而写上对应的xml文件,文件内容如下:

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhenqi.dao.CityZtreeDao">

    <resultMap id="resultCity" type="com.zhenqi.entity.CityZtree">
        <id property="id" column="id" />
        <result property="cityName" column="city_name" />
        <result property="parentId" column="parent_id" />
    </resultMap>

    <select id="findCityZtreeByParentId" parameterType="String" resultMap="resultCity">
        select * from city_ztree where parent_id=#{parentId}
    </select>

    <select id="hasChild" parameterType="String" resultType="Integer">
        select count(1) from city_ztree where parent_id=#{id}
    </select>
</mapper>

再者写个Service实现业务逻辑处理。先建个接口,然后再建个实现接口的实现类。

代码语言:javascript复制
package com.zhenqi.service;

import com.zhenqi.entity.CityZtree;

import java.util.List;
import java.util.Map;

/**
 * Created by wuming on 2019/4/5.
 */
public interface CityZtreeService {

    public List<CityZtree> findByParentId(String parentId);

    public List<Map<String,Object>> getParent(List<CityZtree> list,String parentId);

    public boolean hasChild(String id);
}
代码语言:javascript复制
package com.zhenqi.service.impl;

import com.zhenqi.dao.CityZtreeDao;
import com.zhenqi.entity.CityZtree;
import com.zhenqi.service.CityZtreeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * Created by wuming on 2019/4/5.
 */
@Service("cityZtreeService")
public class CityZtreeServiceImpl implements CityZtreeService {

    @Autowired
    private CityZtreeDao cityZtreeDao;

    @Override
    public List<CityZtree> findByParentId(String parentId) {
        if(StringUtils.isNotBlank(parentId)){
            parentId=parentId;
        }else{
            parentId="0";
        }
        return cityZtreeDao.findCityZtreeByParentId(parentId);
    }

    @Override
    public List<Map<String, Object>> getParent(List<CityZtree> list,String parentId) {
        List<Map<String,Object>> rootList=new ArrayList<>();
        for(CityZtree cityZtree : list){
            Map<String,Object> cityMap=new HashMap<>();
            cityMap.put("id",cityZtree.getId());
            cityMap.put("name",cityZtree.getCityName());
            if(StringUtils.isNotBlank(parentId)){
                cityMap.put("pId",parentId);
            }else{
                cityMap.put("pId","0");
            }
            if(hasChild(cityZtree.getId())){
                cityMap.put("isParent",true);
            }
            rootList.add(cityMap);
        }
        return rootList;
    }

    @Override
    public boolean hasChild(String id) {
        Integer count=cityZtreeDao.hasChild(id);
        if(count>0)
            return true;
        return false;
    }
}

当然,是时候来写个controller类了!

代码语言:javascript复制
package com.zhenqi.controller;

import com.zhenqi.entity.CityZtree;
import com.zhenqi.service.CityZtreeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by wuming on 2019/4/5.
 */
@Controller
@RequestMapping
public class ZtreeController {

    @Autowired
    private CityZtreeService cityZtreeService;

    @RequestMapping("/cityZtree/getCityZtree")
    @ResponseBody
    public Object getCityZtree(HttpServletRequest request, HttpServletResponse response){
        String parentId=request.getParameter("parentId");

        List<CityZtree> parentCityList=new ArrayList<>();
            parentCityList=cityZtreeService.findByParentId(parentId);
            return cityZtreeService.getParent(parentCityList,parentId);

    }
}

你要事先下载好Ztree的包,在你的模板文件中引入以下文件:

代码语言:javascript复制
<link rel="stylesheet" type="text/css" href="/static/ztree/css/metroStyle.css">
    <script type="text/javascript" src="/static/ztree/js/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="/static/ztree/js/jquery.ztree.core-3.5.min.js"></script>
    <script type="text/javascript" src="/static/ztree/js/jquery.ztree.excheck-3.5.min.js"></script>

界面完整源码如下:

代码语言:javascript复制
<!DOCTYPE html >
<html>
<head>
    <title>SpringMVC整合Ztree实现树异步加载</title>

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="stylesheet" type="text/css" href="/static/ztree/css/metroStyle.css">
    <script type="text/javascript" src="/static/ztree/js/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="/static/ztree/js/jquery.ztree.core-3.5.min.js"></script>
    <script type="text/javascript" src="/static/ztree/js/jquery.ztree.excheck-3.5.min.js"></script>
    <script type="text/javascript">
        var setting = {

            check: {
                enable: true,
                chkStyle: "radio",
                radioType: "all"
            },
            data: {
                simpleData: {
                    enable: true
                }
            }, callback: {

                onExpand: zTreeOnExpand,
                onClick: function (e, treeId, treeNode, clickFlag) {
                    $.fn.zTree.getZTreeObj("myZtree").checkNode(treeNode, !treeNode.checked, true);
                }
            }
        };

        //加载展开方法
        function zTreeOnExpand(event, treeId, treeNode) {

            var treeNodeId = treeNode.id;
            $.post(
                    '/cityZtree/getCityZtree',
                    {parentId: treeNodeId},
                    function (data) {
                        var tree = $.fn.zTree.getZTreeObj("myZtree");

                        if (!treeNode.zAsync) {
                            tree.addNodes(treeNode, data);
                            treeNode.zAsync = true;
                        } else {
                            tree.reAsyncChildNodes(treeNode, "refresh");
                        }
                    }
            );
        }

        //首次进入加载level为1的
        $(function () {
            $.post(
                    '/cityZtree/getCityZtree',
                    function (data) {
                        $.fn.zTree.init($("#myZtree"), setting, data);

                    }
            );
        });
</script>
</head>
<body style="overflow-y: auto">
<ul id="myZtree" class="ztree"></ul>

</body>
</html>

0 人点赞