关闭

利用JQuery实现网页左侧树形菜单(IE6 IE7 Firefox测试通过)

标签: iefirefox测试jquerymenustring
1243人阅读 评论(1) 收藏 举报
分类:
 

  本次实验项目结构图:

 

1. 定义保存菜单数据的表结构

CREATE TABLE `tb_com_menu_info` (
  `MENU_ID` varchar(8) NOT NULL,
  `MENU_NAME` varchar(30) DEFAULT NULL,
  `MENU_LINK` varchar(100) DEFAULT NULL,
  `MLEVEL` int(11) DEFAULT NULL,
  `PARENT_CODE` varchar(8) DEFAULT NULL,
  `USE_FLAG` varchar(1) DEFAULT 'Y',
  PRIMARY KEY (`MENU_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `tb_com_menu_info`
(`MENU_ID`,`MENU_NAME`,`MENU_LINK`,`MLEVEL`,`PARENT_CODE`,`USE_FLAG`) 
values ('10000000','图书管理系统',NULL,1,NULL,'Y'),
('10001000','用户管理',NULL,2,'10000000','Y'),
('10001001','用户列表',NULL,3,'10001000','Y'),
('10001002','用户权限',NULL,3,'10001000','Y'),
('10001003','用户类型',NULL,3,'10001000','Y'),
('10001004','黑名单','http://www.baidu.com?',3,'10001000','Y'),
('10002000','图书管理',NULL,2,'10000000','Y'),
('10002001','查询图书',NULL,3,'10002000','Y'),
('10002002','新增图书',NULL,3,'10002000','Y'),
('10002003','图书借阅',NULL,3,'10002000','Y'),
('10003000','报表查看','http://www.163.com?',2,'10000000','Y'),
('10004000','后台管理',NULL,2,'10000000','Y'),
('10004001','功能1','http://www.sina.com.cn?',3,'10004000','Y'),
('10004002','功能2',NULL,3,'10004000','Y');


 

2. 定义数据库的连接类 

ConnectionPoolManager.java

package com.zhuomuniao.myapp.commons;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * ClassName:ConnectionPoolManager.java
 * Description: 连接池
 */
public class ConnectionPoolManager {

	private static ConnectionPoolManager instance;				// 唯一实例

	static synchronized public ConnectionPoolManager getInstance() {
		if (instance == null) {
			instance = new ConnectionPoolManager();
		}
		return instance;
	}

	private ConnectionPoolManager() {
		try {
			// 装载驱动包类
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			System.out.println("装载数据库驱动包出现异常!");
			e.printStackTrace();
		}
	}

	public Connection getConnection() throws SQLException {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","s2sh","1234asdf");
		} catch (SQLException e) {
			System.out.println("链接数据库发生异常!");
			e.printStackTrace();
		}
		return conn;
	}
}

 

3. 创建DAO类

InterSetDAO.java

package com.zhuomuniao.myapp.modules.interset.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.zhuomuniao.myapp.commons.ConnectionPoolManager;
import com.zhuomuniao.myapp.commons.HashResultCollection;

public class InterSetDAO {

  @SuppressWarnings("unchecked")
	public List<Object> getLeftMenu(int level, String LMenuId) throws Exception{
    Connection conn         = null;
    PreparedStatement pstmt = null;
    ResultSet rs            = null; 
    StringBuffer sql =new StringBuffer();
    List menuList = new ArrayList();
    
    try{
      sql.append(" SELECT                                               ").append("\n");
      sql.append("       MENU_ID,MENU_NAME,PARENT_CODE,MENU_LINK,MLEVEL	").append("\n"); 
      sql.append(" FROM  TB_COM_MENU_INFO                               ").append("\n");
      sql.append(" WHERE USE_FLAG='Y'                                   ").append("\n");
      sql.append("   AND MLEVEL=?                                       ").append("\n");
      if(level==1) sql.append("   AND MENU_ID=?                      		").append("\n");
      sql.append(" ORDER BY MENU_ID                                     ").append("\n");
      
      conn = ConnectionPoolManager.getInstance().getConnection();
      pstmt = conn.prepareStatement(sql.toString());
      pstmt.setInt(1, level);
      if(level==1) pstmt.setString(2, LMenuId);
      rs = pstmt.executeQuery();
      
      menuList = new HashResultCollection(rs).getResultList();
      
    }catch(Exception e){
      e.printStackTrace();
    }finally{
      if (rs != null) {rs.close(); rs = null; }
      if (pstmt != null) {pstmt.close(); pstmt = null; }
      if (conn != null) { conn.close(); conn = null; }
    }
    return menuList;
  }
	
}

 

4. 创建DAO中用到的将结果集转化成List对象的类

HashResultCollection.java

package com.zhuomuniao.myapp.commons;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HashResultCollection {
	@SuppressWarnings("unchecked")
	private List			resultList	= new ArrayList();
	private ResultSet	rs					= null;

	public HashResultCollection(ResultSet rs) {
		this.rs = rs;
	}

	@SuppressWarnings("unchecked")
	private Object doCreateRow(ResultSet rs) throws SQLException {
		Map result = new HashMap();
		ResultSetMetaData rsmd = rs.getMetaData();
		int count = rsmd.getColumnCount();
		for (int i = 1; i <= count; i++) {
			String label = rsmd.getColumnLabel(i);
			Object value = rs.getObject(i);
			value = value == null ? "" : value;
			result.put(label.toUpperCase(), value);
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public List getResultList() {
		try {
			while (rs.next()) {
				Object obj = this.doCreateRow(rs);
				resultList.add(obj);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultList;
	}

}

 

 5.创建Service类

InterSetService.java

package com.zhuomuniao.myapp.modules.interset.service;

import java.util.List;

import com.zhuomuniao.myapp.modules.interset.dao.InterSetDAO;

public class InterSetService {

  private InterSetDAO	intersetDAO = new InterSetDAO();

	public List<Object> getFrontLeftMenu(int level, String LMenuId) throws Exception{
    List<Object> list = intersetDAO.getLeftMenu(level, LMenuId);
    return list;
  }
	
}


6. 创建Action类

InterSetManagerAction.java

package com.zhuomuniao.myapp.modules.interset.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zhuomuniao.myapp.modules.interset.service.InterSetService;

@SuppressWarnings("serial")
public class InterSetManagerAction extends HttpServlet {
	
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	} 
	
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//获得ServletContext的引用
		ServletContext context = getServletContext();
		InterSetService interSetService = new InterSetService();
		String action = request.getParameter("action");

		try {

			if (action.equals("leftmenu")) {
				String LMenuId = request.getParameter("LMenuId");
				List menuList1 = interSetService.getFrontLeftMenu(1, LMenuId);
				List menuList2 = interSetService.getFrontLeftMenu(2, "");
				List menuList3 = interSetService.getFrontLeftMenu(3, "");

				request.setAttribute("LMenuId", LMenuId);
				request.setAttribute("menuList1", menuList1);
				request.setAttribute("menuList2", menuList2);
				request.setAttribute("menuList3", menuList3);

				RequestDispatcher dispatcher = context.getRequestDispatcher("/WEB-INF/pages/interset/leftMenu.jsp");
	      dispatcher.forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
	
	//中止Servlet  
  public void destroy() {  
  }  
}

 

7. 创建显示菜单的jsp页面

leftMenu.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>

<%@ page import="java.util.HashMap"%>

<jsp:useBean id="menuList1" scope="request" class="java.util.ArrayList"/>
<jsp:useBean id="menuList2" scope="request" class="java.util.ArrayList"/>
<jsp:useBean id="menuList3" scope="request" class="java.util.ArrayList"/>

<%
String LMenuId = (String)request.getAttribute("LMenuId");
%>

<html>
<head>

	<title>LeftMenu</title>
	
	<link href="css/tree.css" rel="stylesheet" type="text/css">
	<script type="text/javascript" src="js/jquery.js"></script>
	<script type="text/javascript" src="js/tree.js"></script>
	
	<script>
		function doGoUrl(mid,mnm,url){
		  parent.location.href=url+"&menuId="+mid+"&menuNm="+mnm;
		}
	</script>
	
</head>

<body>

<div class="tree" style="overflow:hidden;">
ZHUOMUNIAO
<%
StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = new StringBuffer();
StringBuffer sb3 = new StringBuffer();
StringBuffer temp1 = new StringBuffer();
StringBuffer temp2 = new StringBuffer();
StringBuffer temp3 = new StringBuffer();

String menuId1,menuId2,menuId3;
String menuNm1,menuNm2,menuNm3;
String menuLk1,menuLk2,menuLk3;
String pCode1,pCode2,pCode3;
int mLevel1,mLevel2,mLevel3;

//-------------------------------------------------------第1层
for(int i=0;i<menuList1.size();i++){
  HashMap map1 = (HashMap)menuList1.get(i);
  menuId1 = (String)map1.get("MENU_ID");
  menuNm1 = (String)map1.get("MENU_NAME");
  menuLk1 = (String)map1.get("MENU_LINK");
  pCode1  = (String)map1.get("PARENT_CODE");
  mLevel1 = (Integer)map1.get("MLEVEL");

	//-------------------------------------------------------第2层
  for(int j=0;j<menuList2.size();j++){
    HashMap map2 = (HashMap)menuList2.get(j);
    menuId2 = (String)map2.get("MENU_ID");
    menuNm2 = (String)map2.get("MENU_NAME");
    menuLk2 = (String)map2.get("MENU_LINK");
    pCode2  = (String)map2.get("PARENT_CODE");
    mLevel2 = (Integer)map2.get("MLEVEL");

  	//-------------------------------------------------------第3层
    for(int z=0;z<menuList3.size();z++){
      HashMap map3 = (HashMap)menuList3.get(z);
      menuId3 = (String)map3.get("MENU_ID");
      menuNm3 = (String)map3.get("MENU_NAME");
      menuLk3 = (String)map3.get("MENU_LINK");
      pCode3  = (String)map3.get("PARENT_CODE");
      mLevel3 = (Integer)map3.get("MLEVEL");
      if(menuId1.trim().equals(pCode2.trim()) && menuId2.trim().equals(pCode3.trim())){
        if(!menuLk3.equals("")){
        	temp3.append("<li><a href=\"javascript:doGoUrl('"+menuId3+"','"+menuNm3+"','"+menuLk3+"');\">"+menuNm3+"</a></li>\n");
        }else{
        	temp3.append("<li><a>"+menuNm3+"</a></li>\n");
        }
      }
    }
  	
		if(temp3.length()>0){
    	sb3.append("<ul>\n").append(temp3).append("</ul>\n");
    	temp3=new StringBuffer();
		}
		
    if(menuId1.trim().equals(pCode2.trim())){
	    if(!menuLk2.equals("")){
	    	temp2.append("<li><a href=\"javascript:doGoUrl('"+menuId2+"','"+menuNm2+"','"+menuLk2+"');\">"+menuNm2+"</a>\n"+ sb3 +"</li>\n");
	    }else{
	    	temp2.append("<li><a>"+menuNm2+"</a>\n"+ sb3 +"</li>\n");
	    }
    }
    sb3=new StringBuffer();
    
  }

  if(temp2.length()>0){
	  sb2.append("<ul>\n").append(temp2).append("</ul>\n");
	  temp2=new StringBuffer();
  }
  if(mLevel1==1){
  	temp1.append("<li><a>"+menuNm1+"</a>\n"+ sb2 +"</li>\n");
  }
  sb2=new StringBuffer();
  
}
sb1.append("<ul>\n").append(temp1).append("</ul>\n");
out.println(sb1.toString());

%>
</div>
</body>
</html>


 

8. 创建控制菜单展开或者收起的js代码

tree.js 

/*在IE6,IE7,Firefox下测试能正常显示*/
jQuery(function($){
	var tree = $('.tree');
	var togglePlus = '\<button type=\"button\" class=\"toggle plus\"\>\<\/button\>';
	var toggleMinus = '\<button type=\"button\" class=\"toggle minus\"\>\<\/button\>';
	
	// defalt
	tree.find('ul>li:last-child').addClass('last'); 
	tree.find('li>ul').parent('li').prepend(toggleMinus);	 //prepend是向每个匹配的元素内部前置内容
	tree.find('li>ul').parent('li').addClass('open'); 
	
	
	// click toggle
	$('.tree .toggle').click(function(){
		t = $(this);
		t.parent('li').toggleClass('open');
		if(t.parent('li').hasClass('open')){
			t.removeClass('plus').addClass('minus');
			t.parent('li').children('ul').slideDown(100);
		} else {
			t.removeClass('minus').addClass('plus');
			t.parent('li').children('ul').slideUp(100);			
		}
	});

});


 

9. 用到的css样式文件

 tree.css

/*在IE6,IE7,Firefox下测试能正常显示*/

@charset "utf-8";

html,body{width:100%;height:100%;}

body { 
	BACKGROUND-COLOR:#FFFFFF;
	COLOR: #515050;
	FONT-FAMILY: TAHOMA, Dotum;
	FONT-SIZE:11px;
	MARGIN: 0 0 0 0;
	overflow: auto;
	BORDER: 0;
  SCROLLBAR-FACE-COLOR: #FFFFFF; 
  SCROLLBAR-SHADOW-COLOR: #FFFFFF; 
  SCROLLBAR-3DLIGHT-COLOR: #e8e8e8; 
  SCROLLBAR-ARROW-COLOR: #0083CA; 
  SCROLLBAR-DARKSHADOW-COLOR: #e8e8e8; 
  SCROLLBAR-BASE-COLOR: #FFFFF; 
}

/* Tree */
.tree { font-size:12px; font-family:Tahoma, Geneva, sans-serif;}
.tree ul{ list-style:none; margin:0; padding:0;}
.tree ul ul{ margin-left: -5px;}

.tree li{ 
	position:relative;
	padding-left:20px;
	line-height:20px;
	white-space:nowrap;
	background: url('../images/tree/lineTree.gif') no-repeat 9px 0px;
	*zoom:1; /* 触发IE浏览器的haslayout, 解决ie下的浮动,margin重叠等一些问题。*/
}

.tree li.last{ background-position:9px -1766px;}

.tree a{ text-decoration:none; color:#767676;}
.tree a:hover,
.tree a:active,
.tree a:focus{ text-decoration:underline;}

.tree .toggle{ 
	position:absolute; 
	top:0; 
	left:0; 	
	width:20px; 
	height:20px; 
	border:0;
	background: transparent url('../images/tree/btnPlusMinus.gif') no-repeat; 
	cursor:pointer;
}

.tree .toggle.plus{ background-position:5px -15px;}
.tree .toggle.minus{ background-position:5px 5px;}


10.在web.xml 里配置一下servlet

 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
    <servlet-name>InterSet</servlet-name>
    <servlet-class>com.zhuomuniao.myapp.modules.interset.action.InterSetManagerAction</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>InterSet</servlet-name>
    <url-pattern>/interset.do</url-pattern>
  </servlet-mapping>
  
</web-app>


11. 创建测试页面

 test.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" %>

<!-- ***************************************************************************************************************** -->
<!-- LEFT MENU START -->
<!-- ***************************************************************************************************************** -->
<iframe id="lMenu" name="ifrm" src="interset.do?action=leftmenu&LMenuId=10000000" frameborder="0" marginheight="0" marginwidth="0" scrolling="auto" style="width:165px;height:500px;"></iframe>
<!-- ***************************************************************************************************************** -->
<!-- LEFT MENU END -->
<!-- ***************************************************************************************************************** -->


 

 12. 测试结果:

 

 代码下载地址:  http://download.csdn.net/detail/chuzhenbin/4159264

 

==================以上===================

 

 

 

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:27454次
    • 积分:391
    • 等级:
    • 排名:千里之外
    • 原创:9篇
    • 转载:23篇
    • 译文:0篇
    • 评论:5条
    最新评论