现在的位置: 首页 > 编程 > 正文

页面左侧可收缩菜单案例

2017年05月03日 编程 ⁄ 共 15329字 ⁄ 字号 暂无评论

思维导图:

页面效果:

思维导图的事项,有些可以并行有些要串行,视情况而定,做完一部分测试一部分,慢慢来。

1.创建数据库:

 create database menudemo; 

2.创建表:

1 CREATE TABLE menu (
2   id int(11) NOT NULL auto_increment,
3   linkURL varchar(255) default NULL,
4   menuName varchar(255) default NULL,
5   parent_id int(11) default NULL,
6   PRIMARY KEY  (id),
7   KEY FK33155F9A1787B5 (parent_id),
8   CONSTRAINT FK33155F9A1787B5 FOREIGN KEY (parent_id) REFERENCES menu (id)
9 )

好吧,其实这是hibernate自动生成的。id,linkURL,menuName,parent_id这些基本字段,再加上 parent_id 和 id的外键映射。

测试数据后面自动生成。

3.导入hibernate框架,本次用的是hiberante 3.3.2版本,具体过程:

  1)先加入hibernate3.jar、required 下面的jar包

  2) 再加入 annotation 下的包:hibernate-annotations.jar、ejb3-persistence.jar、hibernate-commons-annotations.jar

  3)为了看输出的SQL语句:加入log4j、slf4j-log4j12-1.5.8.jar、log4j.properties

  4)数据库驱动

  5)新建 hibernate.cfg.xml,从api中考进来,改改配置(connection,方言,show_sql,ddlhbm)

  6) 新建一个 pojo ,测试一下是否能生成表了,成功就可以了。

4.编写Menu 类、配置树状映射:

Menu:one-to-many FetchType 设为 EAGER,不然json数据生成由于懒加载会出问题

 1 package com.shawn.bean;
 2 
 3 import java.io.Serializable;
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 
 7 import javax.persistence.CascadeType;
 8 import javax.persistence.Entity;
 9 import javax.persistence.FetchType;
10 import javax.persistence.GeneratedValue;
11 import javax.persistence.Id;
12 import javax.persistence.JoinColumn;
13 import javax.persistence.ManyToOne;
14 import javax.persistence.OneToMany;
15 import javax.persistence.Table;
16 
17 @Entity
18 @Table(name="menu")
19 public class Menu implements Serializable{
20     
21     private static final long serialVersionUID = -7798302038641404427L;
22 
23     private Integer id;
24     
25     //菜单名
26     private String menuName;
27     
28     //链接URL
29     private String linkURL;
30     
31     //子节点(Menu集合)
32     private List<Menu> children = new ArrayList<Menu>();
33     
34     //父节点(Menu)
35     private transient Menu parent;
36 
37     @Id
38     @GeneratedValue
39     public Integer getId() {
40         return id;
41     }
42 
43     public void setId(Integer id) {
44         this.id = id;
45     }
46 
47     public String getMenuName() {
48         return menuName;
49     }
50 
51     public void setMenuName(String menuName) {
52         this.menuName = menuName;
53     }
54 
55     @OneToMany(cascade=CascadeType.ALL,mappedBy="parent",fetch=FetchType.EAGER)
56     public List<Menu> getChildren() {
57         return children;
58     }
59 
60     public void setChildren(List<Menu> children) {
61         this.children = children;
62     }
63 
64     @ManyToOne(fetch=FetchType.EAGER)
65     @JoinColumn(name="parent_id")
66     public Menu getParent() {
67         return parent;
68     }
69 
70     public void setParent(Menu parent) {
71         this.parent = parent;
72     }
73 
74     public String getLinkURL() {
75         return linkURL;
76     }
77 
78     public void setLinkURL(String linkURL) {
79         this.linkURL = linkURL;
80     }
81     
82 }

5.造测试数据,测试bean

测试类:

  1 package com.shawn.bean;
  2 
  3 import java.util.ArrayList;
  4 
  5 import org.hibernate.Query;
  6 import org.hibernate.Session;
  7 import org.hibernate.SessionFactory;
  8 import org.hibernate.cfg.AnnotationConfiguration;
  9 import org.hibernate.tool.hbm2ddl.SchemaExport;
 10 import org.junit.After;
 11 import org.junit.Before;
 12 import org.junit.Test;
 13 
 14 public class MenuTest {
 15     private static SessionFactory sf = null;
 16     
 17     @Before
 18     public void before(){
 19         sf = new AnnotationConfiguration().configure().buildSessionFactory();
 20     }
 21     
 22     @After
 23     public void after(){
 24         if(sf != null){
 25             sf.close();
 26         }
 27     }
 28     
 29     @Test
 30     public void testSchemaExport(){
 31         new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
 32     }
 33     
 34     @Test
 35     public void testMenuSave(){
 36         
 37         /*=========================日常管理=========================*/
 38         
 39         Menu richang = new Menu();//日常管理
 40         richang.setParent(null);
 41         richang.setMenuName("日常管理");
 42         richang.setLinkURL(null);
 43         
 44         Menu huiyi = new Menu();//会议管理
 45         huiyi.setParent(richang);
 46         huiyi.setMenuName("会议管理");
 47         huiyi.setLinkURL("pages/richang/metting_index.jsp");
 48         
 49         Menu gonggao = new Menu();//公告管理
 50         gonggao.setParent(richang);
 51         gonggao.setMenuName("公告管理");
 52         gonggao.setLinkURL("pages/richang/bbc_index.jsp");
 53         
 54         richang.getChildren().add(huiyi);
 55         richang.getChildren().add(gonggao);
 56         
 57         /*=========================考勤管理=========================*/
 58         
 59         Menu kaoqing = new Menu();//考勤管理
 60         kaoqing.setParent(null);
 61         kaoqing.setMenuName("考勤管理");
 62         kaoqing.setLinkURL(null);
 63         
 64         Menu waichu = new Menu();
 65         waichu.setParent(kaoqing);
 66         waichu.setMenuName("外出登记");
 67         waichu.setLinkURL("pages/kaoqing/waichu.jsp");
 68         
 69         Menu qingjia = new Menu();
 70         qingjia.setParent(kaoqing);
 71         qingjia.setMenuName("请假登记");
 72         qingjia.setLinkURL("pages/kaoqing/qingjia.jsp");
 73         
 74         Menu chuchai = new Menu();
 75         chuchai.setParent(kaoqing);
 76         chuchai.setMenuName("出差登记");
 77         chuchai.setLinkURL("pages/kaoqing/chuchai.jsp");
 78         
 79         Menu shangxiaban = new Menu();
 80         shangxiaban.setParent(kaoqing);
 81         shangxiaban.setMenuName("上下班登记");
 82         shangxiaban.setLinkURL("pages/kaoqing/shangxiaban.jsp");
 83         
 84         Menu shangban = new Menu();//上班登记
 85         shangban.setParent(shangxiaban);
 86         shangban.setMenuName("上班登记");
 87         shangban.setLinkURL("pages/kaoqing/shangban.jsp");
 88         
 89         Menu xiaban = new Menu();//下班登记
 90         xiaban.setParent(shangxiaban);
 91         xiaban.setMenuName("下班登记");
 92         xiaban.setLinkURL("pages/kaoqing/xiaban.jsp");
 93         
 94         shangxiaban.getChildren().add(shangban);
 95         shangxiaban.getChildren().add(xiaban);
 96         
 97         kaoqing.getChildren().add(waichu);
 98         kaoqing.getChildren().add(qingjia);
 99         kaoqing.getChildren().add(chuchai);
100         kaoqing.getChildren().add(shangxiaban);
101         /*=========================计划制定=========================*/
102         
103         Menu jihua = new Menu();//计划制定
104         jihua.setParent(null);
105         jihua.setMenuName("计划制定");
106         jihua.setLinkURL(null);
107         
108         Menu qiyePlan = new Menu();
109         qiyePlan.setParent(jihua);
110         qiyePlan.setMenuName("企业计划");
111         qiyePlan.setLinkURL("pages/jihua/qiyePlan.jsp");
112         
113         Menu bumenPlan = new Menu();
114         bumenPlan.setParent(jihua);
115         bumenPlan.setMenuName("部门计划");
116         bumenPlan.setLinkURL("pages/jihua/bumenPlan.jsp");
117         
118         Menu gerenPlan = new Menu();
119         gerenPlan.setParent(jihua);
120         gerenPlan.setMenuName("个人计划");
121         gerenPlan.setLinkURL("pages/jihua/gerenPlan.jsp");
122         
123         jihua.getChildren().add(qiyePlan);
124         jihua.getChildren().add(bumenPlan);
125         jihua.getChildren().add(gerenPlan);
126         /*=========================审核管理=========================*/
127         
128         Menu shenhe = new Menu();//审核管理
129         shenhe.setParent(null);
130         shenhe.setMenuName("审核管理");
131         shenhe.setLinkURL(null);
132         
133         Menu fbApply = new Menu();
134         fbApply.setParent(shenhe);
135         fbApply.setMenuName("发布申请");
136         fbApply.setLinkURL("pages/shenhe/fbApply.jsp");
137         
138         Menu shenheApply = new Menu();
139         shenheApply.setParent(shenhe);
140         shenheApply.setMenuName("审核批示");
141         shenheApply.setLinkURL("pages/shenhe/shenheApply.jsp");
142         
143         shenhe.getChildren().add(fbApply);
144         shenhe.getChildren().add(shenheApply);
145         
146         /*=========================员工管理=========================*/
147         
148         Menu memManage = new Menu();//员工管理
149         memManage.setParent(null);
150         memManage.setMenuName("员工管理");
151         memManage.setLinkURL(null);
152         
153         Menu memAdd = new Menu();
154         memAdd.setParent(memManage);
155         memAdd.setMenuName("员工添加");
156         memAdd.setLinkURL("pages/yuangong/memAdd.jsp");
157         
158         Menu memUpdate = new Menu();
159         memUpdate.setParent(memManage);
160         memUpdate.setMenuName("员工维护");
161         memUpdate.setLinkURL("pages/yuangong/memUpdate.jsp");
162         
163         memManage.getChildren().add(memAdd);
164         memManage.getChildren().add(memUpdate);
165         
166         /*=========================通讯管理=========================*/
167         
168         Menu tongxun = new Menu();//通讯管理
169         tongxun.setParent(null);
170         tongxun.setMenuName("通讯管理");
171         tongxun.setLinkURL(null);
172         
173         Menu tongxun_xianshi = new Menu();
174         tongxun_xianshi.setParent(tongxun);
175         tongxun_xianshi.setMenuName("显示通讯组");
176         tongxun_xianshi.setLinkURL("pages/tongxun/tongxun_xianshi.jsp");
177         
178         Menu tongxun_tianjia = new Menu();
179         tongxun_tianjia.setParent(tongxun);
180         tongxun_tianjia.setMenuName("增加通讯详细信息");
181         tongxun_tianjia.setLinkURL("pages/tongxun/tongxun_add.jsp");
182         
183         tongxun.getChildren().add(tongxun_xianshi);
184         tongxun.getChildren().add(tongxun_tianjia);
185         
186         Session session = sf.getCurrentSession();
187         session.beginTransaction();
188         
189         session.save(richang);
190         session.save(kaoqing);
191         session.save(jihua);
192         session.save(shenhe);
193         session.save(memManage);
194         session.save(tongxun);
195         
196         session.getTransaction().commit();
197     }
198     
199     @Test
200     public void testLoad(){
201         
202         Session session = sf.getCurrentSession();
203         session.beginTransaction();
204         Query query = session.createQuery("from Menu t where t.parent.id is null");
205         //递归输出所有节点
206         ArrayList<Menu> list = (ArrayList<Menu>)query.list();
207         for(Menu menu : list){
208             System.out.println(menu.getMenuName());
209             print(menu,0);
210         }
211         session.getTransaction().commit();
212     }
213     
214     //输出方法
215     private void print(Menu menu,int level) {
216         String preStr = "";
217         for(int i=0;i<level;i++){
218             preStr += "----|";
219         }
220         
221         System.out.println(preStr + menu.getMenuName());
222         for(Menu m:menu.getChildren()){
223             //如果有子节点,则继续往下递归
224             print(m,level+1);
225         }
226     }
227 }

View Code

造好数据,插入。

6.编写DAO类,用HQL查询,返回List<Menu>,获取所有的一级菜单,由于是FetchType.EAGER,所以所有数据是连根拔起了。

DAO类:

 1 package com.shawn.dao;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.hibernate.Query;
 7 import org.hibernate.Session;
 8 
 9 import com.shawn.bean.Menu;
10 
11 public class MenuDAO {
12     
13     @SuppressWarnings("unchecked")
14     public List<Menu> getAllMenu(Session session){
15         List<Menu> list = null;
16         Query query = session.createQuery("from Menu t where t.parent.id is null");
17         list = (ArrayList<Menu>)query.list();
18         return list;
19     }
20     
21 }

View Code

7.Service 类:

 1 package com.shawn.service;
 2 
 3 import java.lang.reflect.Type;
 4 import java.util.List;
 5 
 6 import org.hibernate.Session;
 7 import org.hibernate.SessionFactory;
 8 
 9 import com.google.gson.Gson;
10 import com.google.gson.GsonBuilder;
11 import com.google.gson.reflect.TypeToken;
12 import com.shawn.bean.Menu;
13 import com.shawn.dao.MenuDAO;
14 import com.shawn.util.HibernateUtil;
15 
16 public class GetMenuService {
17     
18     public List<Menu> getMenu(){
19         List<Menu> menus = null;
20         SessionFactory sf = HibernateUtil.getSessionFactory();
21         Session session = sf.getCurrentSession();
22         session.beginTransaction();
23         
24         MenuDAO dao = new MenuDAO();
25         menus = dao.getAllMenu(session);
26 //        Gson gson = new GsonBuilder().setPrettyPrinting().create();
27 //        Type complexType = new TypeToken<List<Menu>>() {}.getType();
28 //        String reljson = gson.toJson(menus,complexType);
29 //        System.out.println(reljson);
30         session.getTransaction().commit();
31         return menus;
32     }
33     
34 }

View Code

9.导入 Struts1,这里不再详述。

  Action 类:

 1 package com.shawn.action;
 2 
 3 import java.lang.reflect.Type;
 4 import java.util.List;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 
 9 import org.apache.struts.action.Action;
10 import org.apache.struts.action.ActionForm;
11 import org.apache.struts.action.ActionForward;
12 import org.apache.struts.action.ActionMapping;
13 
14 import com.google.gson.Gson;
15 import com.google.gson.GsonBuilder;
16 import com.google.gson.reflect.TypeToken;
17 import com.shawn.bean.Menu;
18 import com.shawn.service.GetMenuService;
19 
20 public class IndexAction extends Action {
21     
22     @Override
23     public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
24             HttpServletResponse response) throws Exception {
25         GetMenuService service = new GetMenuService();
26         //获取菜单列表
27         Gson gson = new GsonBuilder().setPrettyPrinting().create();
28         Type complexType = new TypeToken<List<Menu>>() {}.getType();
29         List<Menu> menus = service.getMenu();
30         String reljson = gson.toJson(menus,complexType);
31         System.out.println(reljson);
32         request.getSession().setAttribute("menusJson", reljson);
33         return mapping.findForward("main");
34     }
35     
36 }

View Code

  Struts-config.xml:

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 
 3 <!DOCTYPE struts-config PUBLIC
 4           "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
 5           "http://struts.apache.org/dtds/struts-config_1_3.dtd">
 6 
 7 <struts-config>
 8 
 9 
10     <form-beans>
11     </form-beans>
12 
13 <!-- =========================================== Global Forward Definitions -->
14 
15     <global-forwards>
16         <!-- Default forward to "Welcome" action -->
17         <!-- Demonstrates using index.jsp to forward -->
18         <forward
19             name="welcome"
20             path="/Welcome.do"/>
21     </global-forwards>
22 
23 
24 <!-- =========================================== Action Mapping Definitions -->
25 
26     <action-mappings>
27             <!-- Default "Welcome" action -->
28             <!-- Forwards to Welcome.jsp -->
29         <action
30             path="/Welcome"
31             forward="/pages/Welcome.jsp"/>
32             
33         <action path="/index" type="com.shawn.action.IndexAction">
34             <forward name="main" path="/pages/default.jsp" redirect="false"/>
35         </action>
36 
37     <!-- sample input and input submit actions
38 
39         <action
40             path="/Input"
41             type="org.apache.struts.actions.ForwardAction"
42             parameter="/pages/Input.jsp"/>
43 
44         <action
45             path="/InputSubmit"
46             type="app.InputAction"
47             name="inputForm"
48             scope="request"
49             validate="true"
50             input="/pages/Input.jsp"/>
51 
52             <action
53                 path="/edit*"
54                 type="app.Edit{1}Action"
55                 name="inputForm"
56                 scope="request"
57                 validate="true"
58                 input="/pages/Edit{1}.jsp"/>
59 
60     end samples -->
61     </action-mappings>
62 
63 </struts-config>

View Code

10.编写JSP页面(主页用frameset布局,这里贴出主要的left.jsp页面)

  left.jsp:

  1 <%@ page language="java" contentType="text/html; charset=UTF-8"
  2     pageEncoding="UTF-8"%>
  3 <%@ page import="java.util.List,java.util.ArrayList,com.shawn.bean.Menu" %>
  4 <%
  5     String path = request.getContextPath();
  6     String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  7 %>
  8 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  9 <html>
 10 <base href="<%=basePath %>"/>
 11 <head>
 12 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 13 <title>首頁</title>
 14 <link style="text/css" href="css/common.css" rel="stylesheet"/>
 15 <style type="text/css">
 16 .menuTree{ margin-left:-30px;}
 17 .menuTree div{ padding-left:30px;}
 18 .menuTree div ul{ overflow:hidden; display:none; height:auto;}
 19 .menuTree span{ display:block; height:25px; line-height:25px; padding-left:5px; margin:1px 0; cursor:pointer; border-bottom:1px solid #CCC;}
 20 .menuTree span:hover{ background-color:#e6e6e6; color:#cf0404;}
 21 .menuTree a{ color:#333; text-decoration:none;}
 22 .menuTree a:hover{ color:#06F;}
 23 .btn{ height:30px; margin-top:10px; border-bottom:1px solid #CCC;}
 24 </style>
 25 <script type="text/javascript" src="lib/jquery-1.11.1/jquery.min.js"></script>
 26 </head>
 27 <body>
 28 <div class="btn">
 29 <input name="" type="button" id="btn_open" value="全部展开" />&nbsp;&nbsp;
 30 <input name="" type="button" id="btn_close" value="全部收缩" />
 31 </div>
 32 <div id="menuTree" class="menuTree"></div>
 33 </body>
 34 <script type="text/javascript">
 35 <%
 36     String menusJson = (String)session.getAttribute("menusJson");
 37 %>
 38  var json = <%=menusJson%>;
 39 /*递归实现获取无级树数据并生成DOM结构*/
 40 var str = "";
 41 var forTree = function(o){
 42  for(var i=0;i<o.length;i++){
 43  var urlstr = "";
 44  try{
 45  if(typeof o[i]["linkURL"] == "undefined"){
 46  urlstr = "<div><span>"+ o[i]["menuName"] +"</span><ul>";
 47  }else{
 48  urlstr = "<div><span><a href='"+ o[i]["linkURL"] +"' target='right'>"+ o[i]["menuName"] +"</a></span><ul>"; 
 49  }
 50  str += urlstr;
 51  if(o[i]["children"] != null && o[i]["children"] != ""){
 52  forTree(o[i]["children"]);
 53  }
 54  str += "</ul></div>";
 55  }catch(e){}
 56  }
 57  return str;
 58 }
 59 /*添加无级树*/
 60 document.getElementById("menuTree").innerHTML = forTree(json);
 61 /*树形菜单*/
 62 var menuTree = function(){
 63      //给有子对象的元素加[+-]
 64      $("#menuTree ul").each(function(index, element) {
 65          var ulContent = $(element).html();
 66          var spanContent = $(element).siblings("span").html();
 67          if(ulContent){
 68              $(element).siblings("span").html("[+] " + spanContent);
 69          }
 70      });
 71      
 72      $("#menuTree").find("div span").click(function(){
 73          var ul = $(this).siblings("ul");
 74          var spanStr = $(this).html();
 75          var spanContent = spanStr.substr(3,spanStr.length);
 76          if(ul.find("div").html() != null){
 77              if(ul.css("display") == "none"){
 78                  ul.show(300);
 79                  $(this).html("[-] " + spanContent);
 80              }else{
 81                  ul.hide(300);
 82                  $(this).html("[+] " + spanContent);
 83              }
 84          }
 85      })
 86 }()
 87 
 88 /*展开*/
 89 $("#btn_open").click(function(){
 90  $("#menuTree ul").show(300);
 91  curzt("-");
 92 })
 93 /*收缩*/
 94 $("#btn_close").click(function(){
 95  $("#menuTree ul").hide(300);
 96  curzt("+");
 97 })
 98 function curzt(v){
 99  $("#menuTree span").each(function(index, element) {
100  var ul = $(this).siblings("ul");
101  var spanStr = $(this).html();
102  var spanContent = spanStr.substr(3,spanStr.length);
103  if(ul.find("div").html() != null){
104  $(this).html("["+ v +"] " + spanContent);
105  }
106  }); 
107 }
108 </script>
109 </html>

View Code

效果就是前面的图。

代码链接: https://pan.baidu.com/s/1cAKzmu 密码: qp5v

 

给我留言

您必须 [ 登录 ] 才能发表留言!

×