zTree的调用设使用(跨两个系统,两类技术实现的项目案例SpringMVC+Spring+MyBatis和Struts2+Spring+ibatis框架组合)...

    xiaoxiao2023-06-12  147

    1、从zTree官网上下载zTree的包,zTree的官方网址是:http://www.ztree.me/v3/main.php#_zTreeInfo

    2、引入zTree所需的依赖,例如(jQueryjs自己引入)

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

    <%@ include file="common/common.jsp"%>

     

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <html>

      <head>

        <title>My JSP 'tree.jsp' starting page</title>

        <link rel="stylesheet" type="text/css" href="${scriptsPath}/zTree/css/zTreeStyle/zTreeStyle.css"/>

       <script type="text/javascript" src="${scriptsPath}/jQuery/jquery-1.11.3.min.js" charset="utf-8"></script>

       <script type="text/javascript" src="${scriptsPath}/zTree/js/jquery.ztree.all-3.5.min.js"></script>

      </head>

     

      <body>

        <%--<div style="background:url('${imagesPath}/tree-icon/web.jpg') 0 0 no-repeat; width:100px; height:100px;"></div>--%>

       

        <input id="citySel" type="text" readonly value="" style="width:300px;" onclick="$.websiteChannel.showMenu(); return false;"/>

        <div id="menuContent" class="menuContent" style="width:300px; height:500px; display:none; background:#EFEFEF;">

          <div id="treeDemo" class="ztree" style="margin-top:0; width:180px; height: 300px;"></div>

       </div>

      

       <div id="chnlcode"></div>

       <div id="sitecode"></div>

       <div id="chnlid"></div>

       <div id="nodePath"></div>

     

        <!-- 站点栏目树对应的js -->

       <script type="text/javascript" src="${scriptsPath}/tpl/common/tree.js" charset="utf-8"></script>

      </body>

    </html>

    3、树的tree.js。调用如下:

    $(function(){

       /*

        * name       :Zuoquan Tu

        * mail       :tuzq@XXXXXXX.cn

        * date       :2015/11/25

        * version    :1.0

        * description:

        * CopyRight (C) 2015-11

        */

       (function($){

          /**

           * 添加一个站点栏目树js对应的命名空间,避免污染其它地方的js

           */

          var targetObj = new Object;

          var targetId = '';

          $.treeMb = {

             showMenu:function(input) {

                targetObj = input;

                targetId = $(input).attr("id");

               

                var inputObj = $(input);

                var inputOffset = $(input).position();

                //alert(inputOffset.top + "," + inputOffset.left);

                $("#menuContent_mb").css({left:inputOffset.left + "px", top:inputOffset.top + inputObj.outerHeight() + "px"}).slideDown("fast");

                $("body").bind("mousedown", $.treeMb.onBodyDown);

               

                /**避免js内存溢出*/

                inputObj = null;

                inputOffset = null;

             },

             hideMenu:function() {

                $("#menuContent_mb").fadeOut("fast");

                $("body").unbind("mousedown", $.treeMb.onBodyDown);

             },

             onBodyDown:function(event) {

                if (!(event.target.id == "menuBtn" || event.target.id == "menuContent_mb" || $(event.target).parents("#menuContent_mb").length>0)) {

                    $.treeMb.hideMenu();

                }

             },

             /**

              * 树被点击的时候执行的动作

              */

             onClick:function(e, treeId, treeNode) {

                var zTree = $.fn.zTree.getZTreeObj("treeDiv_mb");

                zTree.checkNode(treeNode, !treeNode.checked, null, true);

                return false;

             },

             /**

              * 树被选中时执行的事件

              */

             onCheck:function(e, treeId, treeNode) {

                var zTree = $.fn.zTree.getZTreeObj("treeDiv_mb"),

                nodes = zTree.getCheckedNodes(true),

                chnlcodeValue = "";

                sitecodeValue = "";

                chnlidValue = "";

                nodePath = ""//显示建的专题位置,"站点"-->"最后一个栏目"的路径

                websiteId ="";

                for (var i=0, length=nodes.length; i<length; i++) {

                    chnlcodeValue += nodes[i].chnlcode + ",";

                    sitecodeValue += nodes[i].sitecode + ",";

                    chnlidValue += nodes[i].id + ",";

                }

                if (chnlcodeValue.length > 0 )

                    chnlcodeValue = chnlcodeValue.substring(0, chnlcodeValue.length-1);

                if (sitecodeValue.length > 0 )

                    sitecodeValue = sitecodeValue.substring(0, sitecodeValue.length-1);

                if (chnlidValue.length > 0 )

                    chnlidValue = chnlidValue.substring(0, chnlidValue.length-1);

               

               

                var pathNodes = treeNode.getPath();

                websiteId = pathNodes[0].id;

                for(var i = 0; i < pathNodes.length; i++) {

                    nodePath += pathNodes[i].name + "/";

                }

               

                $("#chnlcode_mb").val(chnlcodeValue);

                $("#chnlid_mb").val(chnlidValue);

                $("#sitecode_mb").val(sitecodeValue);

                $("#siteid_mb").val(websiteId);

                $("#nodePath_mb").val(nodePath);

               

                $("#"+targetId).val(nodePath);

                 $("#"+targetId).trigger("blur");

                $("#menuContent_mb").hide();

               

                chnlcodeValue = null;

                sitecodeValue = null;

                chnlidValue = null;

                nodePath = null;

                websiteId = null;

             },

             /**

              * 树被展开时执行的事件

              */

             //onExpand(event,treeId,treeNode) {

             // alert(treeNode.tId + "," + treeNode.level + "," + treeNode.name);

             //}

          };

     

          /**

           * 站点栏目树

           */

          var setting = {// 栏目树的配置

             async : {

                treeId:"website-channel-tree",//zTree 的唯一标识,初始化后,等于 用户定义的 zTree 容器的 id属性值

                enable : true,//设置zTree是否开启异步加载模式

                //autoParam:["id","isSite"],

                url : basePath + '/common/getWebsiteTree.action',//注意这里是调用后台的逻辑

                // 提交的参数

                autoParam: ["id","pid"],//异步加载时需要自动提交父节点属性的参数,这里的idpid是传递给上面的getWebsiteTree的参数

                   dataFilter: function(treeId, parentNode, childNodes) {

                       if (!childNodes) return null;

                       for ( var i = 0, l = childNodes.length; i < l; i++) {

                        if (childNodes[i].isSite == 1) {

                           childNodes[i].icon = "/app-tpl-webapp/images/tree-icon/web.jpg";

                           childNodes[i].iconOpen = "/app-tpl-webapp/images/tree-icon/web.jpg";

                           childNodes[i].iconClose = "/app-tpl-webapp/images/tree-icon/web.jpg";

                        } else {

                           childNodes[i].icon = "/app-tpl-webapp/images/tree-icon/channel.jpg";

                           childNodes[i].iconOpen = "/app-tpl-webapp/images/tree-icon/channel.jpg";

                           childNodes[i].iconClose = "/app-tpl-webapp/images/tree-icon/channel.jpg";

                        }

                     }

                       return childNodes;

                   }

             },

             callback: {

                onCheck: $.treeMb.onCheck, //当树被选中后执行的事件

                onClick: $.treeMb.onClick, //当树被点击后执行的事件

                onExpand:$.treeMb.onExpand //当树被展开后执行的事件

              },

              check: {

                enable: true,

                chkStyle: "radio",      //显示的是radio

                radioType: "all"

             },

              data: {

                  simpleData: {

                     enable: true,

                      idKey: "id",     //定义当前显示的节点的id

                      pIdKey: "pid",   //通过定义这个id为了显示层级结构,id代表的节点将在pid的下面。

                      rootPid: "rid",          //自己定义的

                      chnlcode: "chnlcode",   //这里和json中的值相同

                      sitecode: "sitecode",   //这里和json中的值相同

                      rootPId: 0                //开始的时候定义第一级节点的pid的值为0

                  }

              },

             view:{

                showIcon:true    //让图标显示

             }

          };

     

            //若有多棵树,要下面的id不同

          $.fn.zTree.init($("#treeDiv_mb"), setting);

         

          //避免js内存溢出

          setting = null;

       })(jQuery);

    });

     4使用到的json类似如下(只是调用的接口不一样,json数据是一样的):

     5、要调用的后台的写法(下面的方式是通过Spring+SpringMVC+MyBatis的实现方式):

    package com.ucap.tpl.controller.common;

    XXXXXXXXXX

    ;

     

    /**

     * CommonController.java 公用的Controller

     * @attention

     * @author toto

     * @date 2016-5-13

     * @note begin modify by 涂作权 2016-5-13 原始创建

     */

    @Controller

    @RequestMapping(value = "/common",

                  method = {RequestMethod.GET,RequestMethod.POST})

    public class CommonController extends BaseController {

     

           /**

            * 获得站点栏目树

            * @param request

            * @return

            * @attention

            * @author toto

            * @date 2016-5-13

            * @note  begin modify by 涂作权 2016-5-13  原始创建

            */

           @RequestMapping(value="/getWebsiteTree")

           @ResponseBody

           public String getWebsiteTree(HttpServletRequest request,HttpServletResponse response,

                         String id,String pid) {

                  String websiteTree = null;

                 

                  //设置消息头信息

                  setResponeInfo(response);

                 

                  try {

                         websiteTree = websiteService.getWebsiteTree(getSessionUserId(request),id,pid);

                  } catch (Exception e) {

                         e.printStackTrace();

                  }

                 

                  return websiteTree;

           }

    }

    6、要调用的第三方系统的接口写法(注意下面的实现方式是Struts2+ibatis+Spring的实现方式):

    接口中的写法:

    /**

     * 站点服务接口获取站点列表和单个站点信息等。

     *

     * @author toto

     *

     */

    @WebService

    public interface WebsiteService {

     

    /**

        * 获取站点栏目树的信息

        *  

        * @param userId 用户id

        */

       public String getWebsiteTree(String userId,String id,String pid);

    }

    实现的方式:

    @WebService(serviceName = "WebsiteService", endpointInterface = "com.ucap.wcm.WebsiteService")

    public class WebsiteServiceImpl extends LoadObjectSupport implements WebsiteService {

     

    /**

        * 获取站点栏目信息,用于专题

        * userId       :用户名

        * id           :点击树的时候,被点击的站点或子站点或栏目的ID

        * pid          :表示的是被点击的树节点的父节点的id

        */

       public String getWebsiteTree(String userId,String id,String pid) {     

          try {

             List<Map<String, Object>> treeNodeList = new ArrayList<Map<String, Object>>();

             List<Website> siteList = new ArrayList<Website>();

             //表示点击的是最顶层的站点

             if (Validator.isNotNull(userId) && Validator.isNull(id) && Validator.isNull(pid)) {

                try {

                    //获取有权限的站点栏目树   true:表示的是只取其中一级

                    siteList = getWebsiteManager().findSubWebsitesByWebsiteId(userId, null, true, null);

                } catch (WebContentManagementException e) {

                    e.printStackTrace();

                }

                if (!Validator.isEmpty(siteList)) {

                    for (Website website : siteList) {

                       //1:未发布;2:已签发;3:已发布;4:已删除;5:栏目撤销中;6:栏目发布失败;7:栏目撤销发布失败;8:发布中;

                       //如果删除了

                       if ("4".equals(website.getStatus())) {continue;}

                       //只取已发布的

                       //if(!"3".equals(website.getStatus())){continue;}

                       Map<String, Object> map = new HashMap<String, Object>();

                       if (website.getCodeName().equals("default")) {

                          continue;

                       }

                      

                       map.put("id", website.getWebsiteId());

                       map.put("name", website.getName());

                       map.put("pid", website.getParentWebsiteId());

                       map.put("isParent", true);

                       map.put("sitecode", website.getCodeName());

                       map.put("isSite", 1);

                       map.put("icon", "images/web.jpg");

                       map.put("iconOpen", "images/web.jpg");

                       map.put("iconClose", "images/web.jpg");

                       map.put("nocheck", "true");

     

                       treeNodeList.add(map);

                    }

                }

             } else {

                List<Channel> channles = null;

               

                try {

                    //若是0表示的顶层的

                    if ("0".equals(pid)) {

                       //如果是顶层的,直接获得第一级的栏目列表

                       channles = getChannelManager().getAllChannelsByWebsitId(id, userId, false);

                       //channles = getChannelManager().getTopChannelsByWebsiteId(userId, id, true);

                    } else {

                       channles = getChannelManager().getSubChannels(userId, id, true);

                    }

                    //channles = getChannelManager().getAllChannelsByWebsiteId(userId, id);

                    //channles = getChannelManager().getChannel

                } catch (WebContentManagementException e1) {

                    e1.printStackTrace();

                }

                if(!Validator.isEmpty(channles)){

                    for (Channel channel : channles) {

                       //取出删除掉的栏目

                       if ("4".equals(channel.getStatus())) {continue;}

                       //if(!"3".equals(channel.getStatus())){continue;}//只取已发布的

                       Map<String, Object> map = new HashMap<String, Object>();

                       map.put("id", channel.getChannelId());

                       if (null == channel.getParentId() || channel.getParentId().equals("")) {

                          map.put("pid", channel.getWebsite().getWebsiteId());

                       } else {

                          map.put("pid", channel.getParentId());

                       }

     

                       map.put("name", channel.getChannelName());

                       map.put("siteid", channel.getWebsiteId());

                       map.put("isSite", 0);

                       map.put("chnlcode", channel.getCodeName());

                       map.put("sitecode", channel.getWebsite().getCodeName());

                       treeNodeList.add(map);

                    }

                }

               

                QueryCondition queryCondition = new QueryCondition();

                List<Website> websites;

                try {

                    websites = getWebsiteManager().findSubWebsitesByWebsiteId(userId, id, true, queryCondition);

                    if (!Validator.isEmpty(websites)) {

                       for (Website website : websites) {

                          //只去掉已经删除了的

                          if ("4".equals(website.getStatus())) {continue;}

                         

                          //只取已发布的站点

                          //if(!"3".equals(website.getStatus())){continue;}

                         

                          Map<String, Object> map = new HashMap<String, Object>();

                          if (website.getCodeName().equals("default")) {

                             continue;

                          }

                          map.put("id", website.getWebsiteId());

                          map.put("name", website.getName());

                          map.put("isParent", true);

                          map.put("sitecode", website.getCodeName());

                          map.put("isSite", 1);

                          map.put("nocheck", "true");

                          treeNodeList.add(map);

                       }

                    }

                } catch (WebContentManagementException e) {

                    e.printStackTrace();

                }

             }

            

             return JSONArray.fromObject(treeNodeList).toString();

          } catch (Exception e) {

             e.printStackTrace();

          }

          return JSONArray.fromObject("").toString();

       }

    }

     
    最新回复(0)