Jquery-UI從伺服器端動態載入生成Tree導航欄

cyfxiaochen發表於2015-03-05

一.實現效果
這裡寫圖片描述

二.首先是匯入需要的包
匯入的包有CSS:jquery.ui.all.css,Javascript包:jquery-latest.js,jquery-ui.min_late.js,jquery.layout-latest.js

三.寫介面程式碼:

<body>
    <!-- 最上方div -->
    <div class="ui-layout-north" style="height: 60px;">
        <div class="toppanne">
            <div class="logo"></div>
            <div class="logstatbar">
                <font color="red"><c:out value="${currentUser.username}"></c:out>
                </font> , 您好,歡迎光臨! <a href="javascript:modifyPassword();" onclick="">修改密碼</a>
                | <a href="questions_reply.jsp" target="pageIfm">幫助</a> | <a
                    href="javascript:isclose();">退出</a>
            </div>
        </div>
    </div>


    <!-- IFRAME as layout-pane -->
    <div class="ui-layout-center">
        <div class="header">
            <div class="header_r"></div>

            <!-- 顯示全屏的按鈕 -->
            <div class="header_l">
                <a href="javascript:void(0);" onclick="ItoggleScreenMode()"
                    id="ScreenModeBar" class="togglefullscreen"></a>
            </div>
            <div class="clear"></div>
        </div>
        <!-- 顯示載入完成 -->
        <iframe src="about:blank" width="100%" name="pageIfm" id="pageIfm"
            class="ui-layout-content" onload="aIfmLoadOk();" height="100%"
            frameborder="0" scrolling="yes"></iframe>
        <div class="footer" align="center">&nbsp;</div>
    </div>

    <!-- 頁面左側 -->
    <div class="ui-layout-west">
        <div class="header"></div>
        <div class="subhead"></div>
        <div class="ui-layout-content">
            <div id="left_menu">
                <div id="img"></div>
            </div>
            <div id="treeboxbox_tree">
                <!-- 此處顯示dwr傳送請求之後從伺服器傳來的menu -->
            </div>
            <div id="tree_down"></div>
            <div>
                <div id="help_top"></div>
                <div id="helpbox"></div>
                <div id="help_down"></div>
            </div>
        </div>
        <div class="footer"></div>

    </div>
    <div id="returnMsgbox"></div>
</body>

四:寫js程式碼:
首先是頁面框架載入時的程式碼:

`<script type="text/javascript">
    var CLayout;
    $(window).load(function() {

        initLayout();
        initMAINMENU();
        try {
            document.execCommand('BackgroundImageCache', false, true)
        } catch (e) {
        }

    });
    function sMSG(txt) {
        $("#returnMsgbox").html(txt).show();
    }

    function hMSG(txt) {
        if (txt) {
            $("#returnMsgbox").html(txt).show();
            setTimeout('$("#returnMsgbox").fadeOut("slow");', 2000);
        } else {
            $("#returnMsgbox").hide();
        }
    }
    function showLoadingBox() {
        sMSG('載入中...請稍候<a href="javascript:void(0);" onclick="hMSG();">[關閉]</a>');
    }
    function openurl(url) {
        sMSG('載入中...請稍候<a href="javascript:void(0);" onclick="hMSG();">[關閉]</a>');
        $("#pageIfm").attr("src", url);
    }
    function initLayout() {
        CLayout = $('body').layout({
            closable : true // pane can open & close
            ,
            resizable : true // when open, pane can be resized 
            ,
            slidable : false // when closed, pane can 'slide' open over other panes - closes on mouse-out
            ,
            center__minWidth : 100,
            spacing_closed : 5,
            useStateCookie : false,
            resizable : false,
            north : {
                onclose_end : function() {
                    checkFullScreen();
                },
                onopen_end : function() {
                    checkFullScreen();
                },
                slidable : false // OVERRIDE the pane-default of 'slidable=true'
                ,
                togglerLength_closed : 100 // toggle-button is full-width of resizer-bar
                ,
                spacing_closed : 20 // big resizer-bar when open (zero height)
                ,
                spacing_closed : 0,
                spacing_open : 0,
                resizable : false
            },
            west : {
                onclose_end : function() {
                    checkFullScreen();
                },
                onopen_end : function() {
                    checkFullScreen();
                },
                minSize : 100,
                showOverflowOnHover : false,
                togglerLength_open : 48,
                slidable : false,
                togglerLength_closed : 48,
                spacing_closed : 3,
                spacing_open : 3,
                resizable : false
            }
        });
    }
    function toggleScreenMode(o) {
        var oh = $(o).html();
        if (oh == "全屏") {
            screenMode(3);
            $(o).html("退出全屏");
        } else {
            screenMode(2);
            $(o).html("全屏");
        }
    }
    var IsFullScreen = false;//當前是否全屏
    function checkFullScreen() {
        var ns = CLayout.state["north"].isVisible;
        var ws = CLayout.state["west"].isVisible;
        if (ns || ws) {
            IsFullScreen = false;
            $("#ScreenModeBar").removeClass("togglefullscreenOn");
        } else {
            IsFullScreen = true;
            $("#ScreenModeBar").addClass("togglefullscreenOn");
        }
    }
    function ItoggleScreenMode() {

        if (!IsFullScreen) {
            screenMode(3);
            $("#ScreenModeBar").addClass("togglefullscreenOn");
            IsFullScreen = true;
        } else {
            screenMode(2);
            $("#ScreenModeBar").removeClass("togglefullscreenOn");
            IsFullScreen = false;
        }
    }
    function screenMode(v) {
        switch (v) {
        case 0:

            CLayout.changePinStat('north', false);
            CLayout.changePinStat('south', false);
            CLayout.changePinStat('west', true);
            CLayout.changePinStat('east', false);
            break;
        case 1:
            CLayout.open('north');
            //CLayout.open('south');
            CLayout.open('west');
            CLayout.open('east');
            break;
        case 2:

            CLayout.changePinStat('north', true);
            CLayout.changePinStat('south', false);
            CLayout.changePinStat('west', true);
            CLayout.changePinStat('east', false);
            break;
        case 3:
            CLayout.changePinStat('north', false);

            CLayout.changePinStat('west', false);

            break;
        }
    }
    function toggleSUBMENU(id) {
        $(".subnavbox[id!='subnavbox_" + id + "']").hide()
        $("#subnavbox_" + id).slideToggle("fast");
    }

    function initMAINMENU() {
        $(".mainnavsubtitle").each(function() {
            switch ($(this).attr("tti")) {
            case "系統管理":
                $(this).addClass("icon_sys");
                break;
            case "採購類報表":
                $(this).addClass("icon_cg");
                break;
            case "出入庫類報表":
                $(this).addClass("icon_crk");
                break;
            case "庫存類報表":
                $(this).addClass("icon_kc");
                break;
            case "處方類報表":
                $(this).addClass("icon_cf");
                break;

            }
        });
    }
    function aIfmLoadOk() {

        $("#returnMsgbox").html("載入完成").show();
        setTimeout('$("#returnMsgbox").fadeOut("slow");', 2000);
    }

    function isclose() {
        if (confirm("確定要退出系統嗎?")) {
            parent.window.location = "user!logout";
        }
    }
    function modifyPassword() {
        digStr = "dialogHeight:480px;dialogWidth:1024px;center:yes";
        window.parent.showModalDialog("common/modifyPassword.jsp", "", digStr);
    }
</script>

接下來是DWR的Javascript實現程式碼:

<script type="text/javascript">
    $.ajaxSetup({
        cache : false
    });

    loadTree("<c:out value='${currentUser.username}' />");

    function loadTree(loginName) {
        var result;
        DWREngine.setAsync(false);
        check
                .queryTree(
                        loginName,
                        function(data) {
                            result = data;
                            $(result)
                                    .find("itemp")
                                    .each(
                                            function(i) {
                                                var title = $(this)
                                                        .attr("text");
                                                var opt = '<div title="'+title+'" id = "mainnavsubtitle_'+i+'">'
                                                        + '<div class="mainnavsubtitle" tti="'+title+'">'
                                                        + ' <a href="javascript:void(0)" hidefocus="hidefocus" onclick="toggleSUBMENU('
                                                        + i
                                                        + ');">'
                                                        + '     <strong>'
                                                        + title
                                                        + '</strong>'
                                                        + '</a>'
                                                        + '</div>'
                                                        + '<div class="subnavbox" id="subnavbox_'+i+'">';
                                                $(this)
                                                        .find("item")
                                                        .each(
                                                                function(j) {
                                                                    var tits = $(
                                                                            this)
                                                                            .attr(
                                                                                    "text");
                                                                    var purl = $(
                                                                            this)
                                                                            .attr(
                                                                                    "PageUrl");
                                                                    var onv = "";
                                                                    if (purl
                                                                            .indexOf('(') != -1) {
                                                                        onv = purl;
                                                                    } else {
                                                                        onv = "openurl('"
                                                                                + purl
                                                                                + "');";
                                                                    }
                                                                    opt += '<a title="'
                                                                            + tits
                                                                            + '" id ="imtems_'
                                                                            + j
                                                                            + '" href="javascript:void(0);" onclick="'
                                                                            + onv
                                                                            + '" target="_self">'
                                                                            + tits
                                                                            + '</a>';
                                                                });
                                                opt += '</div></div>';
                                                $("#treeboxbox_tree").append(
                                                        opt);
                                            });
                        });
    }
</script>

五.伺服器端程式碼的編寫:
首先需要配置DWR.xml

        <create creator="new" javascript="check">
            <param name="class" value="com.yaofang.util.Check"></param>
            <include method="queryTree"/>
        </create>

Check.java

public class Check {

    public View getNodes(int id) throws Exception{
        List<Node> nodes = null;

        if (id == 0){   // return the first level nodes
            nodes = Node.findAll(Node.class, "parentId=0 or parentId is null", null);
        } else {    // return the children nodes
            nodes = Node.findAll(Node.class, "parentId=?", new Object[]{id});
        }

        List<Map<String,Object>> items = new ArrayList<Map<String,Object>>();
        for(Node node: nodes){
            Map<String,Object> item = new HashMap<String,Object>();
            item.put("id", node.id);
            item.put("text", node.name);

            // the node has children, 
            // set the state to 'closed' so the node can asynchronous load children nodes 
            if (node.hasChildren()){
                item.put("state", "closed");
            }
            items.add(item);
        }

        return new JsonView(items);
    }

    public String queryTree(String LOGIN_NAME) {
        List list = new ArrayList();
        String sql = "select RESOURCE_ID,RESOURCE_NAME,MODULE_PATH,RESOURCE_LEVEL,HIGHER_ID,PARAMETER from SYS_RESOURCE";

        String xmlTree = "";
        try {
            list = dbUtil.executeQuery2(sql);
            if (list.size() > 0) {
                // 將list轉換為Tree;
                Tree t = traversalList(list);
                // 將Tree轉換為XML;
                TreeConverter tc = new TreeConverter();
                xmlTree = tc.buildTree(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return xmlTree;
    }
    public Tree traversalList(List list) {
        Tree t = new Tree();
        t.setId("main");

        // itemps所有1級選單
        List<Itemp> itemps = new ArrayList<Itemp>();

        // items所有2級選單
        List<Item> items = new ArrayList<Item>();

        for (int i = 0; i < list.size(); i++) {

            String level = (String) ((List) list.get(i)).get(3);

            if (level.equals(CommonVar.Resource_Level1)) {
                Itemp itemp = new Itemp();
                itemp.setId((String) ((List) list.get(i)).get(5));
                itemp.setText((String) ((List) list.get(i)).get(1));
                itemp.setIm0("folderOpen.gif");
                itemp.setIm1("folderOpen.gif");
                itemp.setIm2("folderClosed.gif");
                itemp.setOpen("1");
                itemp.setSelect("false");
                itemp.setHigherID((String) ((List) list.get(i)).get(0));
                itemp.setPageUrl("#");
                itemps.add(itemp);
            } else if (level.equals(CommonVar.Resource_Level2)) {
                Item item = new Item();
                item.setId((String) ((List) list.get(i)).get(5));
                item.setIm0("ico_29.gif");
                item.setIm1("ico_29.gif");
                item.setIm2("ico_29.gif");
                item.setPageTarget("pageIfm");
                item.setPageUrl((String) ((List) list.get(i)).get(2));
                item.setText((String) ((List) list.get(i)).get(1));
                item.setHigherID((String) ((List) list.get(i)).get(4));
                items.add(item);
            }
        }

        for (Itemp ip : itemps) {
            List<Item> is = new ArrayList<Item>();
            for (Item i : items) {
                if (i.getHigherID().equals(ip.getHigherID()))
                    is.add(i);
            }
            ip.setItem(is);
        }

        t.setItemps(itemps);

        return t;
    }
}

實體類:
ITem.java

    private String text;
    private String id;
    private String im0;
    private String im1;
    private String im2;
    private String PageUrl;
    private String PageTarget;
    private String HigherID;

Itemp.java

    private String text;
    private String id;
    private String PageUrl;
    private String open;
    private String im0;
    private String im1;
    private String im2;
    private String select;
    private String HigherID;
    private List<Item> item;

Tree.java

    private List<Itemp> itemps = new ArrayList<Itemp>();
    private String id;

轉換器類:
TreeConverter.java

public class TreeConverter{

    public static String buildTree(Tree tree) {
        XStream xs = new XStream(new DomDriver());
        xs.alias("tree", Tree.class);

        xs.alias("itemp", Itemp.class);
        xs.alias("item", Item.class);

        xs.aliasAttribute(Tree.class, "id", "id");

        // 遍歷類的屬性
        Field[] fields = Itemp.class.getDeclaredFields(); // 獲取實體類的所有屬性,返回Field陣列
        for (Field f : fields) { // 遍歷所有屬性
            if (f.getType().equals(String.class))
                xs.aliasAttribute(Itemp.class, f.getName(), f.getName());
        }

        Field[] fields2 = Item.class.getDeclaredFields(); // 獲取實體類的所有屬性,返回Field陣列
        for (Field f : fields2) { // 遍歷所有屬性
            if (f.getType().equals(String.class))
                xs.aliasAttribute(Item.class, f.getName(), f.getName());
        }

        String xml = xs.toXML(tree);

        xml = replaceLast(xml, "<itemps>\n", "");
        xml = replaceLast(xml, "</itemps>\n", "");
        xml = replaceLast(xml, "<item>\n", "");
        xml = replaceLast(xml, "</item>\n", "");

        xml = "<?xml version='1.0' encoding='utf-8'?>\n" + xml;

        //System.out.println(xml);

        return xml;
    }

    public static void main(String args[]) throws Exception {
        // 裝配tree
        Tree t = new Tree();
        t.setId("main");

        // 裝配Itemp
        List<Itemp> itList = new ArrayList<Itemp>();

        Itemp it1 = new Itemp();
        it1.setId("xxgl");
        it1.setIm0("folderOpen.gif");
        it1.setIm1("folderOpen.gif");
        it1.setIm2("folderClosed.gif");
        it1.setOpen("1");
        it1.setPageUrl("#");
        it1.setSelect("false");
        it1.setText("許可權管理");

        // 裝配Item
        List<Item> iList1 = new ArrayList<Item>();
        Item i1 = new Item();
        i1.setId("zygl");
        i1.setIm0("ico_29.gif");
        i1.setIm1("ico_29.gif");
        i1.setIm2("ico_29.gif");
        i1.setPageTarget("pageIfm");
        i1.setPageUrl("userlist.do?method=queryResourceList");
        i1.setText("資源管理");

        Item i2 = new Item();
        i2.setId("jsgl");
        i2.setIm0("ico_29.gif");
        i2.setIm1("ico_29.gif");
        i2.setIm2("ico_29.gif");
        i2.setPageTarget("pageIfm");
        i2.setPageUrl("userlist.do?method=queryRoleList");
        i2.setText("角色管理");

        iList1.add(i1);
        iList1.add(i2);
        it1.setItem(iList1);


        Itemp it2 = new Itemp();
        it2.setId("jcxxgl");
        it2.setIm0("folderOpen.gif");
        it2.setIm1("folderOpen.gif");
        it2.setIm2("folderClosed.gif");
        it2.setOpen("0");
        it2.setPageUrl("#");
        it2.setSelect("false");
        it2.setText("基礎資訊管理");

        // 裝配Item
        List<Item> iList2 = new ArrayList<Item>();
        Item i3 = new Item();
        i3.setId("ypxxgl");
        i3.setIm0("ico_29.gif");
        i3.setIm1("ico_29.gif");
        i3.setIm2("ico_29.gif");
        i3.setPageTarget("pageIfm");
        i3.setPageUrl("medicine.do?method=queryMedicine");
        i3.setText("藥品資訊管理");

        Item i4 = new Item();
        i4.setId("yfgl");
        i4.setIm0("ico_29.gif");
        i4.setIm1("ico_29.gif");
        i4.setIm2("ico_29.gif");
        i4.setPageTarget("pageIfm");
        i4.setPageUrl("medicine.do?method=queryPharmacy");
        i4.setText("藥房管理");

        iList2.add(i3);
        iList2.add(i4);
        it2.setItem(iList2);

        itList.add(it1);
        itList.add(it2);
        t.setItemps(itList);

        System.out.println("裝配完成");

        XStream xs = new XStream(new DomDriver());
        xs.alias("tree", Tree.class);

        xs.alias("itemp", Itemp.class);
        xs.alias("item", Item.class);

        xs.aliasAttribute(Tree.class, "id", "id");

        // 遍歷類的屬性
        Field[] fields = Itemp.class.getDeclaredFields(); // 獲取實體類的所有屬性,返回Field陣列
        for (Field f : fields) { // 遍歷所有屬性
            if (f.getType().equals(String.class))
                xs.aliasAttribute(Itemp.class, f.getName(), f.getName());
        }

        Field[] fields2 = Item.class.getDeclaredFields(); // 獲取實體類的所有屬性,返回Field陣列
        for (Field f : fields2) { // 遍歷所有屬性
            if (f.getType().equals(String.class))
                xs.aliasAttribute(Item.class, f.getName(), f.getName());
        }

        String xml = xs.toXML(t);

        xml = replaceLast(xml, "<itemps>\n", "");
        xml = replaceLast(xml, "</itemps>\n", "");
        xml = replaceLast(xml, "<item>\n", "");
        xml = replaceLast(xml, "</item>\n", "");

        System.out.println(xml);
    }

    public static String replaceLast(String string, String toReplace,
            String replacement) {
        Pattern p = Pattern.compile(toReplace);
        Matcher m = p.matcher(string);
        string = m.replaceAll(replacement);
        return string;
    }

}

六.資料庫的建立:
這裡寫圖片描述

相關文章