基于EasyUI的基础之上实现树形功能菜单
程序员文章站
2022-06-03 13:52:27
页面展示截图如下:
为了实现以上效果,在开始前必须先将环境配置一下。
第一步: 首先,先将 jquery-easyui-1.2.6 文件引入到工程项目下,并在jsp...
页面展示截图如下:
为了实现以上效果,在开始前必须先将环境配置一下。
第一步: 首先,先将 jquery-easyui-1.2.6 文件引入到工程项目下,并在jsp页面上进入引入3个jsp文件和2个css文件。如下:
<span style="font-size:14px;"> </span><span style="font-size:14px; white-space: pre;"> </span><span style="font-family:courier new;font-size:12px;"><script type="text/javascript" src="jquery-easyui-1.2.6/jquery-1.7.2.min.js"></script> <link rel="stylesheet" type="text/css" href="jquery-easyui-1.2.6/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="jquery-easyui-1.2.6/themes/icon.css"> <script type="text/javascript" src="jquery-easyui-1.2.6/jquery.easyui.min.js"></script> <script type="text/javascript" src="jquery-easyui-1.2.6/locale/easyui-lang-zh_cn.js"></script></span>
引入顺序必须按照以上顺序引入,否则页面展示效果将出错。
第二步:引入jar包,分别为:commons-beanutils-1.8.3.jar、commons-collections-3.2.1.jar、commons-lang-2.5.jar、commons-logging-1.1.1.jar、ezmorph-1.0.6.jar、json-lib-2.3-jdk15.jar、mysql-connector-java-5.1.17-bin.jar
代码实现
1、创建数据表
<span style="font-size:14px;">drop database easyui; create database easyui; use easyui; show tables; #创建菜单表 create table menu( id int(11) not null auto_increment, ####菜单id### name varchar(20) default null, ####菜单名#### url varchar(100) default null, #### 菜单url#### checked varchar(10) default null, ####菜单是否被选中 icon varchar(30) default null, ####菜单图标#### parent_id int(11) default null, ####父节点菜单的id#### primary key(id) ####id是主键#### ); #插入测试数据 ####测试数据#### insert into menu(id,name,url,checked,icon,parent_id) values (1,'权限菜单',null,'',null,0), (2,'用户管理',null,'0',null,1), (3,'岗位管理',null,'',null,1), (4,'资源管理',null,'',null,1), (5,'用户功能1',null,'',null,2), (6,'岗位功能1',null,'0',null,3), (7,'资源功能2','/easyui/index.jsp','0',null,3), (8,'资源功能1','sss','0',null,4), (9,'岗位功能2',null,'',null,3), (10,'资源功能3','111','0',null,4), (11,'资源管理4','222','',null,4), (14,'岗位功能3','dfds',null,null,3), (17,'用户功能2','sss','0',null,2); #查看数据 select * from menu; //查询跟节点 select * from menu where parent_id=0; #查看指定父节点下有哪些子节点 select * from menu where parent_id=2;</span><span style="font-size:24px;"> </span>
2、jdbc连接工具类
jdbcutils.java
<span style="font-family:courier new;font-size:12px;">package com.hsj.utils; import java.sql.connection; import java.sql.drivermanager; import java.sql.preparedstatement; import java.sql.resultset; import java.sql.sqlexception; public class jdbcutils { static { try { class.forname("com.mysql.jdbc.driver"); } catch (classnotfoundexception e) { e.printstacktrace(); } } public static connection getconnection() throws exception { return drivermanager.getconnection( "jdbc:mysql:///easyui?useunicode=true&characterencoding=utf-8", "root", "zxczxc"); } public static void close(resultset rs, preparedstatement ps, connection conn) { try { if (rs != null) rs.close(); } catch (exception e) { e.printstacktrace(); } finally { try { if (ps != null) ps.close(); } catch (exception e) { e.printstacktrace(); } finally { try { if (conn != null) conn.close(); } catch (exception e) { e.printstacktrace(); } } } } }</span><span style="font-size:24px;"> </span>
3、创建实体类domain
menu.java
<span style="font-family:courier new;font-size:12px;">package com.hsj.domain; public class menu { private int id; //菜单id private string name; //菜单名 private string url; //菜单链接的网址 private string checked; //菜单是否被选中 private string icon; //菜单图标 private int parent_id; //当前菜单的父节点id public menu(){} public menu(int id, string name, string url, string checked, string icon,int parentid) { this.id = id; this.name = name; this.url = url; this.checked = checked; this.icon = icon; parent_id = parentid; } public int getid() { return id; } public void setid(int id) { this.id = id; } public string getname() { return name; } public void setname(string name) { this.name = name; } public string geturl() { return url; } public void seturl(string url) { this.url = url; } public string getchecked() { return checked; } public void setchecked(string checked) { this.checked = checked; } public string geticon() { return icon; } public void seticon(string icon) { this.icon = icon; } public int getparent_id() { return parent_id; } public void setparent_id(int parentid) { parent_id = parentid; } } </span>
treedtd.java
<span style="font-family:courier new;font-size:12px;">package com.hsj.domain; import java.util.hashmap; import java.util.map; public class treedto { private int id; private string text; private string iconcls; private string checked; private int parent_id; private string state; /** * 自定义属性信息 */ private map<string, object> attributes = new hashmap<string, object>(); public treedto() { } public treedto(int id, string text, string iconcls, string checked, int parent_id, string state, map<string, object> attributes) { this.id = id; this.text = text; this.iconcls = iconcls; this.checked = checked; this.parent_id = parent_id; this.state = state; this.attributes = attributes; } public int getid() { return id; } public void setid(int id) { this.id = id; } public string gettext() { return text; } public void settext(string text) { this.text = text; } public string geticoncls() { return iconcls; } public void seticoncls(string iconcls) { this.iconcls = iconcls; } public string getchecked() { return checked; } public void setchecked(string checked) { this.checked = checked; } public int getparent_id() { return parent_id; } public void setparent_id(int parentid) { parent_id = parentid; } public string getstate() { return state; } public void setstate(string state) { this.state = state; } public map<string, object> getattributes() { return attributes; } public void setattributes(map<string, object> attributes) { this.attributes = attributes; } @override public string tostring() { return "treedto [attributes=" + attributes + ", checked=" + checked + ", iconcls=" + iconcls + ", id=" + id + ", parent_id=" + parent_id + ", state=" + state + ", text=" + text + "]"; } } </span>
4、创建接口dao
meundao.java
<span style="font-family:courier new;font-size:12px;">package com.hsj.dao; import java.util.list; import com.hsj.domain.menu; import com.hsj.domain.treedto; public interface menudao{ /** * 根据父节点的值查询所有的子节点 * @param parentid * @return */ public list<treedto> getchildrenbyparentid(string parentid); /** * 根据id值查询当前对象 * @param id * @return */ public menu findmenubyid(int id); /** * 保存指定对象 * @param <t> * @param t */ public <t> void save(t t); /** * 修改菜单对象 * @param menu */ public void update(menu menu); /** * 根据id删除指定对象 * @param id */ public void delete(int id); /** * 根据父节点删除当前父节点下所有的子节点 * @param parentid 父节点id */ public void deletechildrenbyparentid(int parentid); /** * 根据当前节点 的id值删除它的所有子节点 * @param id */ public void deletechildren(int id); } </span>
5、实现dao接口方法bean
menudaobean.java
<span style="font-family:courier new;font-size:12px;">package com.hsj.dao.bean; import java.lang.reflect.field; import java.lang.reflect.method; import java.sql.connection; import java.sql.preparedstatement; import java.sql.resultset; import java.util.arraylist; import java.util.hashmap; import java.util.list; import java.util.map; import com.hsj.dao.menudao; import com.hsj.domain.menu; import com.hsj.domain.treedto; import com.hsj.utils.jdbcutils; public class menudaobean implements menudao{ public <t> int gettotalrecord(class<t> clazz) { // todo auto-generated method stub return 0; } public <t> void save(t t) { //1.根据对象得到类模板对象 class<t> clazz= (class<t>) t.getclass(); //2.得到当前类中所有字段组成的数组,不管访问权限如何,但不包括父类中的字段 field[] fields=clazz.getdeclaredfields(); //insert into t_menu(field1,field2,....) values(value1,value2,....) list<string> key=new arraylist<string>();//key用来存储字段列表 list<object> value=new arraylist<object>();//value用来存储值列表 string methodname=null; method method=null; for(int i=0;i<fields.length;i++) { try { //getname methodname="get"+getmethodname(fields[i].getname()); method=clazz.getmethod(methodname); object o=method.invoke(t); if(o!=null && !"id".equals(fields[i].getname())) { key.add(fields[i].getname()); value.add(o); } } catch (exception e) { e.printstacktrace(); }; } //组拼sql语句 //string table=clazz.getname().substring(clazz.getname().lastindexof(".")+1); string table=clazz.getsimplename(); stringbuffer sql= new stringbuffer("insert into "+table+" ("); stringbuffer values=new stringbuffer(" values("); for(int i=0;i<value.size();i++) { sql.append(key.get(i)+","); values.append("?,"); } //insert into menu (name,url) sql.deletecharat(sql.length()-1).append(")"); //values(?,?) values.deletecharat(values.length()-1).append(")"); //insert into menu (name,url) values(?,?) sql.append(values); connection conn=null; preparedstatement ps=null; try { conn=jdbcutils.getconnection(); ps=conn.preparestatement(sql.tostring()); //只有object[]不为空且数组中有元素 if(key!=null && key.size()>0) { for(int i=0;i<key.size();i++) { ps.setobject(i+1,value.get(i)); } } system.out.println(ps.tostring()); ps.execute(); system.out.println("添加成功"); } catch (exception e) { e.printstacktrace(); }finally{ jdbcutils.close(null, ps, conn); } } /** * 将该字符串的一个字母变成大写 * @param fildename 字符串 * @return * @throws exception */ private static string getmethodname(string fieldname) throws exception { byte[] items = fieldname.getbytes(); items[0] = (byte) ((char) items[0] - 'a' + 'a'); return new string(items); } /** * 根据菜单的父id找到他所有的子菜单并存储到集合中 */ public list<treedto> getchildrenbyparentid(string parentid) { connection conn = null; preparedstatement ps = null; resultset rs = null; list<menu> menus=new arraylist<menu>(); list<treedto> treedtos=new arraylist<treedto>(); try { string sql=""; if(parentid==null || "".equals(parentid)) { sql="select * from menu where parent_id=0"; }else{ sql="select * from menu where parent_id="+parentid; } conn=jdbcutils.getconnection(); ps=conn.preparestatement(sql); rs=ps.executequery(); while(rs.next()) { menu menu=new menu(); menu.setid(rs.getint("id")); menu.seticon(rs.getstring("icon")); menu.seturl(rs.getstring("url")); menu.setchecked(rs.getstring("checked")); menu.setname(rs.getstring("name")); menu.setparent_id(rs.getint("parent_id")); menus.add(menu); } }catch(exception e){ e.printstacktrace(); }finally{ jdbcutils.close(rs, ps, conn); } for(menu m : menus) { treedto td=new treedto(); td.setid(m.getid()); td.settext(m.getname()); td.setchecked(m.getchecked()); td.seticoncls(m.geticon()); td.setparent_id(m.getparent_id()); list<menu> childrenlist=getchildren(m.getid()); if(childrenlist.size()>0) { td.setstate("closed"); }else{ td.setstate("open"); } map<string,object> attributes=new hashmap<string,object>(); attributes.put("url", m.geturl()); td.setattributes(attributes); treedtos.add(td); } return treedtos; } /** * 根据当前菜单的主键值找到当前菜单有哪些子菜单对象组成的集合并返回 * @param id * @return */ public list<menu> getchildren(int id) { connection conn = null; preparedstatement ps = null; resultset rs = null; list<menu> menus=new arraylist<menu>(); try { conn=jdbcutils.getconnection(); ps=conn.preparestatement("select * from menu where parent_id="+id); rs=ps.executequery(); while(rs.next()) { menu menu=new menu(); menu.setid(rs.getint("id")); menu.seticon(rs.getstring("icon")); menu.seturl(rs.getstring("url")); menu.setchecked(rs.getstring("checked")); menu.setname(rs.getstring("name")); menu.setparent_id(rs.getint("parent_id")); menus.add(menu); } } catch(exception e) { e.printstacktrace(); }finally{ jdbcutils.close(rs, ps, conn); } return menus; } /** * 根据菜单的主键查找当前菜单对象 */ public menu findmenubyid(int id) { connection conn = null; preparedstatement ps = null; resultset rs = null; menu menu=null; try { conn=jdbcutils.getconnection(); ps=conn.preparestatement("select * from menu where id="+id); rs=ps.executequery(); if(rs.next()) { menu=new menu(); menu.setid(rs.getint("id")); menu.seticon(rs.getstring("icon")); menu.seturl(rs.getstring("url")); menu.setchecked(rs.getstring("checked")); menu.setname(rs.getstring("name")); menu.setparent_id(rs.getint("parent_id")); } } catch(exception e) { e.printstacktrace(); }finally{ jdbcutils.close(rs, ps, conn); } return menu; } public void update(menu menu) { connection conn = null; preparedstatement ps = null; resultset rs = null; try { conn=jdbcutils.getconnection(); ps=conn.preparestatement("update menu set name=?,url=?,checked=?,icon=?,parent_id=? where id=?"); ps.setstring(1, menu.getname()); ps.setstring(2, menu.geturl()); ps.setstring(3, menu.getchecked()); ps.setstring(4, menu.geticon()); ps.setint(5, menu.getparent_id()); ps.setint(6, menu.getid()); ps.executeupdate(); } catch(exception e) { e.printstacktrace(); }finally{ jdbcutils.close(rs, ps, conn); } } /** * 根据主键删除当前菜单对象 */ public void delete(int id) { connection conn = null; preparedstatement ps = null; resultset rs = null; try { conn=jdbcutils.getconnection(); ps=conn.preparestatement("delete from menu where id="+id); ps.executeupdate(); } catch(exception e) { e.printstacktrace(); }finally{ jdbcutils.close(rs, ps, conn); } } /** * 根据当前菜单的主键值删除当前菜单的所有子菜单及当前菜单对象 */ public void deletechildren(int id) { list<menu> menus=getchildren(id); for(int i=0;i<menus.size();i++) { int cid=menus.get(i).getid(); //delete(cid); deletechildren(cid); } delete(id); } /** * 根据菜单的父id删除所有子菜单 */ public void deletechildrenbyparentid(int parentid) { connection conn = null; preparedstatement ps = null; resultset rs = null; try { conn=jdbcutils.getconnection(); ps=conn.preparestatement("delete from menu where parent_id="+parentid); system.out.println("========="+ps.tostring()); ps.executeupdate(); } catch(exception e) { e.printstacktrace(); }finally{ jdbcutils.close(rs, ps, conn); } } } </span>
6、创建servlet 并配置映射文件
menuservlet.java
<span style="font-family:courier new;font-size:12px;">package com.hsj.servlet; import java.io.ioexception; import java.io.printwriter; import java.util.list; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import net.sf.json.jsonarray; import com.hsj.dao.menudao; import com.hsj.dao.bean.menudaobean; import com.hsj.domain.menu; import com.hsj.domain.treedto; public class menuservlet extends httpservlet { public void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { this.dopost(request, response); } public void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { response.setcontenttype("text/html;charset=utf-8"); printwriter out = response.getwriter(); string method = request.getparameter("method"); if (method != null && !"".equals(method) && "getmenu".equals(method)) { getmenu(request, response); } else if (method != null && !"".equals(method) && "changemenu".equals(method)) { changemenu(request, response); } else if (method != null && !"".equals(method) && "addmenu".equals(method)) { addmenu(request, response); } else if (method != null && !"".equals(method) && "updatemenu".equals(method)) { updatemenu(request, response); } else if (method != null && !"".equals(method) && "deletemenu".equals(method)) { deletemenu(request, response); } out.flush(); out.close(); } /** * 删除当前菜单及其当前菜单的所有子菜单 * @param request * @param response */ private void deletemenu(httpservletrequest request, httpservletresponse response) { string id=request.getparameter("id"); menudao menudao=new menudaobean(); system.out.println(id); menudao.deletechildren(integer.valueof(id)); } /** * 修改菜单 * @param request * @param response */ private void updatemenu(httpservletrequest request, httpservletresponse response) { string id=request.getparameter("id"); string name=request.getparameter("name"); string url=request.getparameter("url"); menudao menudao=new menudaobean(); menu menu=menudao.findmenubyid(integer.valueof(id)); menu.setname(name); menu.seturl(url); menudao.update(menu); } /** * 添加菜单 * @param request * @param response */ private void addmenu(httpservletrequest request,httpservletresponse response) { string parentid=request.getparameter("parentid"); string name=request.getparameter("name"); string url=request.getparameter("url"); menu menu=new menu(); menu.setname(name); menu.seturl(url); menu.setparent_id(integer.valueof(parentid)); menudao menudao=new menudaobean(); menudao.save(menu); } /** * 菜单菜单的父菜单 * @param request * @param response */ private void changemenu(httpservletrequest request, httpservletresponse response) { string targetid= request.getparameter("targetid"); string sourceid= request.getparameter("sourceid"); string point= request.getparameter("point"); system.out.println("point="+point); menudao menudao=new menudaobean(); menu target= menudao.findmenubyid(integer.valueof(targetid)); menu source= menudao.findmenubyid(integer.valueof(sourceid)); if("append".equals(point)) { //源菜单作为目标菜单的子菜单 source.setparent_id(target.getid()); }else{ //源菜单和目标菜单使用相同的父菜单的id值 source.setparent_id(target.getparent_id()); } menudao.update(source); } /** * 根据父id得到它所有的子菜单 * @param request * @param response */ private void getmenu(httpservletrequest request,httpservletresponse response) { system.out.println("getmenu-------"); //获取当前展的节点的id try { string parentid=request.getparameter("id"); menudao menudao=new menudaobean(); list<treedto> treedtos=menudao.getchildrenbyparentid(parentid); system.out.println(treedtos.tostring()); response.setcontenttype("text/html;charset=utf-8"); string json=jsonarray.fromobject(treedtos).tostring(); response.getwriter().write(json); system.out.println("json="+json); } catch (exception e) { e.printstacktrace(); } } } </span>
映射文件信息:
web.xml
<span style="font-family:courier new;"><?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"> <servlet> <servlet-name>menuservlet</servlet-name> <servlet-class>com.hsj.servlet.menuservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>menuservlet</servlet-name> <url-pattern>/menuservlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app></span>
7、jsp网页代码
<span style="font-family:courier new;"><%@ 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> <base href="<%=basepath%>"> <title>tree的使用</title> <script type="text/javascript" src="jquery-easyui-1.2.6/jquery-1.7.2.min.js"></script> <link rel="stylesheet" type="text/css" href="jquery-easyui-1.2.6/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="jquery-easyui-1.2.6/themes/icon.css"> <script type="text/javascript" src="jquery-easyui-1.2.6/jquery.easyui.min.js"></script> <script type="text/javascript" src="jquery-easyui-1.2.6/locale/easyui-lang-zh_cn.js"></script> <script type="text/javascript"> var flag; $(function(){ $("#t1").tree({ url:"menuservlet?method=getmenu", animate:true,//展开和折叠菜单时会伴随着动画 dnd:true,//启动菜单项的拖拽功能 //checkbox:true,//菜单项前面是否显示复选框 /* point的取值可能为: append:源节点作为目标节点的子节点 top:源节点和目标节点使用相同的父节点,并且源节点在目标节点的上面 bottom:源节点会产生在目标节点的下面,并且和目标节点是兄弟关系,并且源节点在目标节点的下面 */ ondrop:function(target, source, point){//当拖拽节点松手时触发 //获取目标节点对象 var tar=$("#t1").tree("getnode",target); $.ajax({ type:"post", url:"menuservlet?method=changemenu", data:{ targetid:tar.id, sourceid:source.id, point:point }, datatype:"json", cache:false, success:function(result){ $.messager.show({ title:"提示信息", msg:"操作成功" }); } }); }, oncontextmenu: function(e,node){ //禁止浏览器的右键菜单 e.preventdefault(); $(this).tree('select', node.target); $('#mm').menu('show', { left: e.pagex, top: e.pagey }); } }); $("#savebtn").click(function(){ if(flag=="add") { //1.获取所选中的节点 var parent=$("#t1").tree("getselected"); $("#t1").tree("append",{ parent:parent.target, data:[{ text:$("#dialogmenu").find("input[name=name]").val(), attributes:{url:$("#dialogmenu").find("input[name=url]").val()} }] }); //后台更新 $.ajax({ type:"post", url:"menuservlet?method=addmenu", cache:false, data:{ parentid:parent.id, name:$("#dialogmenu").find("input[name=name]").val(), url:$("#dialogmenu").find("input[name=url]").val() }, datatype:"json", success:function(result){ //重新加载tree $("#t1").tree("reload",parent.target); $.messager.show({ title:"提示信息", msg:"操作成功" }); } }); }else{ $.ajax({ type:"post", url:"menuservlet?method=updatemenu", cache:false, data:{ id:$("#dialogmenu").find("input[name=id]").val(), name:$("#dialogmenu").find("input[name=name]").val(), url:$("#dialogmenu").find("input[name=url]").val() }, datatype:"json", success:function(result){ //重新加载tree,刷新所选中的节点的父节点 var node=$("#t1").tree("getselected"); var parentnode=$("#t1").tree("getparent",node.target); $("#t1").tree("reload",parentnode.target); $.messager.show({ title:"提示信息", msg:"操作成功" }); } }); } //关闭dialog $("#dialog").dialog("close"); }); $("#cancelbtn").click(function(){ $("#dialog").dialog("close"); }); }); function append(){ flag="add"; $("#dialogmenu").form("clear"); $("#dialog").dialog("open"); } function removes(){ //前台更新 //选中的节点 var selectenode=$("#t1").tree("getselected"); $("#t1").tree("remove",selectenode.target); //后台更新 $.post("menuservlet?method=deletemenu",{id:selectenode.id},function(result){ $.messager.show({ title:"提示信息", msg:"操作成功" }); }); } function editor(){ flag="edit"; //清空表单,把选中的节点填充到该dialog中,包括:id,name,url $("#dialogmenu").form("clear"); //选中的节点 var selectenode=$("#t1").tree("getselected"); //填充数据 $("#dialogmenu").form("load",{ id:selectenode.id, name:selectenode.text, url:selectenode.attributes.url }); //打开dialog $("#dialog").dialog("open"); } </script> </head> <body> <div id="mm" class="easyui-menu" style="width:120px;"> <div onclick="append()">append</div> <div onclick="editor()">editor</div> <div onclick="removes()">remove</div> </div> <ul id="t1"></ul> <div id="dialog" title="设置权限" class="easyui-dialog" style="width:400px" closed=true modal=true> <form id="dialogmenu" method="post"> <input type="hidden" name="id"/> <table> <tr> <td>名称:</td> <td><input type="text" name="name"/></td> </tr> <tr> <td>url:</td> <td><input type="text" name="url"/></td> </tr> <tr> <td colspan="2"> <input id="savebtn" type="button" value="保存"/> <input id="cancelbtn" type="button" value="取消"/> </td> </tr> </table> </form> </div> </body> </html> </span>