ztree+java非同步載入樹形菜單例子

來源:互聯網
上載者:User

本篇給大家分享一下 ztree+java非同步載入demo。ztree支援載入資料量可以做大,預計一個頁面5000+都是可以的。

Ztree非同步載入的意思就是: 當點擊展開樹節點時,才去請求後台action返回點擊節點的子節點資料並載入。

本demo採用SpringMvc+Mybatis。參見代碼結構圖:


前台代碼jsp:

 代碼如下 複製代碼

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ztree</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css"
    href="<%=request.getContextPath()%>/css/zTreeStyle.css">
<script type="text/javascript"
    src="<%=request.getContextPath()%>/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript"
    src="<%=request.getContextPath()%>/js/jquery.ztree.core.js"></script>
<script type="text/javascript"
    src="<%=request.getContextPath()%>/js/jquery.ztree.excheck.min.js"></script>
<script type="text/javascript">
   /**
    *非同步載入的意思就是: 當點擊展開樹節點時,
    *才去請求後台action返回點擊節點的子節點
    *資料並載入。
    */
    var setting = {
        data : {
            key:{
                name:"catalogName"
            },
            simpleData : {
                enable : true,
                idKey:"catalogId",
                pIdKey:"parentId",
            }
        },
        async : {
            enable : true,
            url : "ztree/list.ht",
            autoParam : [ "catalogId", "catalogName" ],
            dataFilter : filter
        //非同步返回後經過Filter
        },
        callback : {
            // beforeAsync: zTreeBeforeAsync, // 非同步載入事件之前得到相應資訊
            OnAsyncSuccess : zTreeOnAsyncSuccess,//非同步載入成功的fun
            aOnAsyncError : zTreeOnAsyncError, //載入錯誤的fun
            beforeClick : beforeClick,//捕獲單擊節點之前的事件回呼函數
            onRightClick: zTreeOnRightClick
        }
    };
    //treeId是treeDemo,非同步載入完之後走這個方法
    function filter(treeId, parentNode, childNodes) {
        if (!childNodes)
            return null;
        childNodes = eval(childNodes);
        return childNodes;
    }
    //點擊節點觸發事件
    function beforeClick(treeId, treeNode) {
        if (!treeNode.isParent) {
            alert("請選擇父節點");
            return false;
        } else {
            return true;
        }
    }
    //非同步載入失敗走該方法
    function zTreeOnAsyncError(event, treeId, treeNode) {
        alert("非同步載入失敗!");
    }
    //非同步載入成功走該方法
    function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
    }
    //右擊事件
    function zTreeOnRightClick(){
        alert("asdas");
    }
    /**********當你點擊父節點是,會非同步訪問controller,把id傳過去*************/
    var zNodes = [];
    $(document).ready(function() {
        $.fn.zTree.init($("#treeDemo"), setting, zNodes);
    });
</script>
</head>
<body>
    <div style="height:600px; width:98%">
        <div style="height:600px; width:20%; border:1px solid #999999; float:left">
            <ul id="treeDemo" class="ztree"></ul>
        </div>
        <div style="height:600px; width:79.5%; border:1px solid #999999; float:left; overflow:auto">
            <iframe id="testIframe" name="testIframe" frameborder=0 scrolling=auto width=90%  height=580px src="ztree/welcome.ht"></iframe>
        </div>
    </div>
</body>
</html>


幕後處理邏輯:

 代碼如下 複製代碼

package com.henu.controller;
import java.io.PrintWriter;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.henu.model.Ztree;
import com.henu.service.ZtreeService;
@Controller
@RequestMapping("/ztree/")
public class ZtreeController {
    @Resource
    private ZtreeService ztreeService;
    
    @RequestMapping("page")
    public String page(){
        return "ztree/ztreeList";
    }
    
    @RequestMapping("welcome")
    public String welcome(){
        return "ztree/welcome";
    }
    
    @RequestMapping("list")
    public void list(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String catalogIdParam = request.getParameter("catalogId");
        Long catalogId = null;
        if (catalogIdParam != null) {
            catalogId = Long.parseLong(catalogIdParam);
        }
        String catalogName = request.getParameter("catalogName");
        System.out.println(catalogId + "|" + catalogName + "|"); 
        List<Ztree> ztreeList = ztreeService.getZtree(catalogId); 
        PrintWriter out = response.getWriter();
        String str = JSONArray.fromObject(ztreeList).toString();
        System.out.println(str);
        out.print(str);
    }
}

服務代碼Service層ZtreeService.java:

 代碼如下 複製代碼

package com.henu.service;
import java.util.List;
import com.henu.model.Ztree;
public interface ZtreeService {
    List<Ztree> getZtree(Long catalogId);
}

ServiceImpl層ZtreeServiceImpl.java:

 代碼如下 複製代碼

package com.henu.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.henu.dao.ZtreeDAO;
import com.henu.model.Ztree;
import com.henu.service.ZtreeService;
@Service
public class ZtreeServiceImpl implements ZtreeService{
    @Resource
    private ZtreeDAO ztreeDAO;
    public List<Ztree> getZtree(Long catalogId) {
        return ztreeDAO.getZtree(catalogId);
    }
}

持久層ZtreeDAO:

 代碼如下 複製代碼

package com.henu.dao;
import java.util.List;
import javax.annotation.Resource;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Component;
import com.henu.model.Ztree;
@Component
public class ZtreeDAO {
    @Resource
    private SqlSessionTemplate sqlSessionTemplate;
    
    public List<Ztree> getZtree(Long catalogId) {
        List<Ztree> ztreeList = sqlSessionTemplate.selectList("com.henu.model.Ztree.getZtree",catalogId);
        return ztreeList;
    }
}

Ztree.map.xml

 

 代碼如下 複製代碼
<?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,namespace的值習慣上設定成包名+sql對應檔名,這樣就能夠保證namespace的值是唯一的
例如namespace="com.henu.mapping.userMapper"就是com.henu.mapping(包名)+userMapper(userMapper.xml檔案去除尾碼)
 -->
<mapper namespace="com.henu.model.Ztree">
    <select id="getZtree" resultType="com.henu.model.Ztree">
        select * from henu_catalog where 1=1
        <if test="_parameter!=null and _parameter!='' "> 
            and parentId = #{_parameter,jdbcType=NUMERIC}
        </if>
        <if test="_parameter == null "> 
            and parentId = 1
        </if>
        order by catalogId
    </select>
</mapper>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.