用layui完成 tree/權限(二星)/增刪改查javascript
寫一個簡單的登陸界面(根據用戶的id來獲取相對應的權限)css
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <link rel="stylesheet" href="${pageContext.request.contextPath }/static/js/layui/css/layui.css" media="all"> </head> <body> <form action="${pageContext.request.contextPath }/userAction.action?methodName=login" method="post" style="margin-left: 36%;margin-top: 150px"> <div class="layui-form-item"> <label class="layui-form-label">帳號:</label> <div class="layui-input-inline"> <input type="text" name="uid" class="layui-input" lay-verify="account" placeholder="帳號" autocomplete="on" maxlength="20"/> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">密碼:</label> <div class="layui-input-inline"> <input type="password" name="user_pwd" class="layui-input" lay-verify="password" placeholder="密碼" maxlength="20"/> </div> </div> <div class="layui-form-item" style="margin-left: 140px"> <input type="submit" class="layui-btn btn-submit" lay-filter="sub" value="當即登陸"> </div> </form> </body> </html>
UserDaohtml
package com.chenjiahao.dao; import java.util.List; import java.util.Map; import org.w3c.dom.ls.LSInput; import com.chenjiahao.util.JsonBaseDao; import com.chenjiahao.util.JsonUtils; import com.chenjiahao.util.PageBean; import com.chenjiahao.util.StringUtils; public class UserDao extends JsonBaseDao { /** * 登陸 * * @param map * @param pageBean * @return * @throws Exception */ public List<Map<String, Object>> list(Map<String, String[]> map, PageBean pageBean) throws Exception { String sql = "SELECT * FROM t_user WHERE TRUE"; String uid = JsonUtils.getParamVal(map, "uid"); String upwd = JsonUtils.getParamVal(map, "user_pwd"); if (StringUtils.isNotBlank(uid)) { sql = sql + " and uid=" + uid; } if (StringUtils.isNotBlank(upwd)) { sql = sql + " and upwd=" + upwd; } return super.executeQuery(sql, pageBean); } /** * 看這個用戶有什麼權限 * * @param uid * @param pageBean * @return * @throws Exception */ public List<Map<String, Object>> listMenu(String uid, PageBean pageBean) throws Exception { String sql = "SELECT * FROM t_usermenu WHERE TRUE "; if (StringUtils.isNotBlank(uid)) { sql = sql + " AND uid='" + uid + "'"; } return super.executeQuery(sql, null); } }
UserAction(將用戶的ID放入index)java
package com.chenjiahao.web; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.chenjiahao.dao.UserDao; import com.chenjiahao.util.PageBean; import com.chenjiahao.util.ResponseUtil; import com.fasterxml.jackson.databind.ObjectMapper; import com.zking.framework.ActionSupport; public class UserAction extends ActionSupport { private UserDao userDao = new UserDao(); /** * 樹形菜單查詢 * * @param request * @param response * @return * @throws Exception */ public String login(HttpServletRequest request, HttpServletResponse response) throws Exception { List<Map<String, Object>> list = this.userDao.list(request.getParameterMap(), null); //.get(0).get"uid if (list != null && list.size() > 0) { List<Map<String, Object>> listMenu = this.userDao.listMenu(request.getParameter("uid"), null); StringBuilder sb = new StringBuilder(); for (Map<String, Object> map : listMenu) { sb.append("," + map.get("Menuid")); } request.setAttribute("menuHid", sb.substring(1)); } else { return "login"; } return "index"; } }
index界面( 樹形菜單展現界面 注意layui css 和 js 文件的引用)node
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <link rel="stylesheet" href="${pageContext.request.contextPath }/static/js/layui/css/layui.css" media="all"> <link rel="stylesheet" href="${pageContext.request.contextPath }/static/js/layui/css/index.css" > <script src="${pageContext.request.contextPath }/static/js/layui/layui.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery-3.3.1.js"></script> </head> <body > <input type="hidden" id="menuHid" value="${menuHid }"> <div class="layui-layout layui-layout-admin " id="app"> <div class="layui-header"> <div class="layui-logo">後臺管理界面</div> <!-- 頭部區域(可配合layui已有的水平導航) --> <ul class="layui-nav layui-layout-right"> <li class="layui-nav-item"><a href="#" onclick="exit()">退出登陸</a></li> </ul> </div> <!-- 左邊tree頁面 --> <div class="layui-side layui-bg-black"> <div class="layui-side-scroll "> <div id="demo" ></div> </div> </div> <!-- 選項卡要顯示的地方 --> <div class="layui-body" > <div class="layui-tab" lay-filter="tabs" lay-allowClose="true" > <ul class="layui-tab-title"> </ul> <div class="layui-tab-content"> </div> </div> </div> <div class="layui-footer" align="center" > <!-- 底部固定區域 --> © layui.com - 底部固定區域 </div> </div> <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/layui/layui.all.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/index.js"></script> </body> </html>
index.jsjquery
$(function () { console.info($("#menuHid").val()); $.ajax({ type: "post", url: "menuAction.action?methodName=treeMenu&&menuHid="+$("#menuHid").val(), dataType: "json", /*data: {// 傳給servlet的數據, role_id: MenuHid, right_code: "-1", d: new Date() },*/ success: function (data) { console.info(data); layui.tree({ elem: '#demo',// 傳入元素選擇器 nodes: data, // spread:true, click: function (node) {// 點擊tree菜單項的時候 var element = layui.element; var exist = $("li[lay-id='" + node.id + "']").length; //判斷是否是用重複的選項卡 if (exist > 0) { element.tabChange('tabs', node.id);// 切換到已有的選項卡 } else { if (node.attributes.MenuURL != null && node.attributes.MenuURL != "") {// 判斷是否須要新增選項卡 element.tabAdd( 'tabs', { title: node.name, content: '<iframe scrolling="yes" frameborder="0" src=" ' + node.attributes.MenuURL + ' " width="100%" height="100%"></iframe>'// 支持傳入html , // width="99%" height="99%" id: node.id }); element.tabChange('tabs', node.id); } } } }); } }); })
MenuDaoweb
package com.chenjiahao.dao; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.chenjiahao.entity.TreeNode; import com.chenjiahao.util.JsonBaseDao; import com.chenjiahao.util.JsonUtils; import com.chenjiahao.util.PageBean; import com.chenjiahao.util.StringUtils; public class MenuDao extends JsonBaseDao { private static final Map<String, String[]> TreeNode = null; /** * * @param map * request.getParameterMap * @param pageBean * 分頁 * @return * @throws SQLException * @throws IllegalAccessException * @throws InstantiationException */ public List<TreeNode> list(Map<String, String[]> map, PageBean pageBean) throws Exception { List<Map<String, Object>> listMenu = this.listMenuSet(map, pageBean); List<TreeNode> treeNodeList = new ArrayList<>(); menu2TreeNodelist(listMenu, treeNodeList); return treeNodeList; } public List<Map<String, Object>> listMenuSet(Map<String, String[]> map, PageBean pageBean) throws Exception { String sql = "select * from t_menu where true"; String id = JsonUtils.getParamVal(map, "menuHid"); if (StringUtils.isNotBlank(id)) { sql = sql + " and menuid in (" + id + ")"; } else { sql = sql + " and menuid=-1"; } return super.executeQuery(sql, pageBean); } /** * 查詢menu表的數據 * * @param map * @param pageBean * @return * @throws SQLException * @throws IllegalAccessException * @throws InstantiationException */ public List<Map<String, Object>> listMenu(Map<String, String[]> map, PageBean pageBean) throws Exception { String sql = "select * from t_menu where true"; String id = JsonUtils.getParamVal(map, "id"); if (StringUtils.isNotBlank(id)) { sql = sql + " and parentid=" + id; } else { sql = sql + " and parentid=-1"; } return super.executeQuery(sql, pageBean); } /** * menu表的數據格式不符合easyui樹形展現格式 須要轉換成easyui所能識別的格式 * * @param map * @param treeNode * @throws SQLException * @throws IllegalAccessException * @throws InstantiationException */ private void menu2TreeNode(Map<String, Object> map, TreeNode treeNode) throws Exception { treeNode.setId(map.get("Menuid").toString()); treeNode.setName(map.get("Menuname").toString()); treeNode.setAttributes(map); // 遞歸 Map<String, String[]> jspMap = new HashMap<>(); jspMap.put("id", new String[] { treeNode.getId() }); List<Map<String, Object>> listMenu = this.listMenu(jspMap, null); List<TreeNode> treeNodeList = new ArrayList<>(); // 循環將數據取出來 menu2TreeNodelist(listMenu, treeNodeList); treeNode.setChildren(treeNodeList); } private void menu2TreeNodelist(List<Map<String, Object>> mapList, List<TreeNode> treeNodeList) throws Exception { TreeNode treeNode = null; for (Map<String, Object> map : mapList) { treeNode = new TreeNode(); menu2TreeNode(map, treeNode); treeNodeList.add(treeNode); } } }
MenuActionajax
package com.chenjiahao.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.chenjiahao.dao.MenuDao; import com.chenjiahao.entity.TreeNode; import com.chenjiahao.util.ResponseUtil; import com.fasterxml.jackson.databind.ObjectMapper; import com.zking.framework.ActionSupport; public class MenuAction extends ActionSupport { private MenuDao menuDao = new MenuDao(); public String treeMenu(HttpServletRequest request, HttpServletResponse response) throws Exception { List<TreeNode> list = this.menuDao.list(request.getParameterMap(), null); ObjectMapper om = new ObjectMapper(); String jsonStr = om.writeValueAsString(list); ResponseUtil.write(response, jsonStr); return null; } }
manage.jsp書本類別sql
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <link rel="stylesheet" href="${pageContext.request.contextPath }/static/js/layui/css/layui.css" > <script src="${pageContext.request.contextPath }/static/js/layui/layui.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery-3.3.1.js"></script> </head> <body class="child-body"> <div class="child-nav"> <span class="layui-breadcrumb"> <a>書籍類別管理</a> <a><cite>分類列表</cite></a> </span> </div> <blockquote class="layui-elem-quote"> <!--搜索維度 --> <div class="layui-form"> <div class="layui-form-item"> <label class="layui-form-label">書籍名稱</label> <div class="layui-input-inline"> <input type="text" id='uname' name="booktypename" lay-verify="required" placeholder="請輸入書籍名" autocomplete="true" class="layui-input"> </div> <button class="layui-btn layui-btn-normal layui-btn-radius" data-type="reload"><i class="layui-icon"></i>查詢</button> <button class="layui-btn layui-btn-normal" data-type="add">新建</button> </div> </div> </blockquote> <!--隱藏域傳值 --> <input type="hidden" id="sj" value="${pageContext.request.contextPath}" > <!--根據table id 來展現表格數據 --> <table class="layui-hide" id="test" lay-filter="test"></table> <!--行內樣式按鈕 --> <script type="text/html" id="lineBtns"> <a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon"></i>編輯</a> <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">刪除</a> </script> <!--彈出層 --> <div class="site-text" style="margin: 5%; display: none" id="box1" target="test123"> <form class="layui-form layui-form-pane" onsubmit="return false" id="booktype"> <div class="layui-form-item"> <label class="layui-form-label">類型編號</label> <div class="layui-input-block"> <input type="text" class="layui-input layui-disabled text_add " id="book_category_id" name=book_category_id disabled="disabled"> </div> <br> <label class="layui-form-label"> 書本類別名</label> <div class="layui-input-block"> <input type="text" class="layui-input" id="book_category_name" name=book_category_name><br> </div> </div> </form> </div> </body> <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/manage.js"></script> </html>
manage.js數據庫
$(function () { //執行渲染 layui.use(['table','layer','form'],function(){ var data=document.getElementById("sj").value; var table =layui.table; var layer=layui.layer; var form = layui.form; /*展現數據表格 */ table.render({ elem:'#test'//表格id ,url:data+'/userAction.action?methodName=listcartegory'//所對應調用的接口 ,method:'post' //提交方式 ,cols:[[ /*根據數據庫的表格所對應的名稱 */ {field:'book_category_id',height:80, width:300, title: '書籍類別序號', sort: true} ,{field:'book_category_name', height:80,width:300, title: '書籍類別名稱'} ,{field:'right',height:80, width:300, title: '操做', toolbar:'#lineBtns'}//操做欄 ]] ,page:'true'//分頁 , id: 'testReload' }); //上方菜單操做欄(查詢、以及 增長 按鈕 ) var $ = layui.$, active = { //查詢 reload: function () { var uname = $('#uname');//書籍類別名稱 根據 id來取值 console.log(uname.val()); // 執行重載 table.reload('testReload', { page: { curr: 1 // 從新從第 1 頁開始 }, where: { key: 'uname', uname: uname.val(), } }); }, add: function () { //添加 layer.open({//彈出框 type: 1, title: '添加書本類別', maxmin: true, shadeClose: true, //點擊遮罩關閉層 area: ['300px', '400px'], content: $('#box1'), btn: ['肯定', '取消'], yes: function (index, layero) {//肯定執行函數 console.log(layero); //執行添加方法 $.getJSON(data+"/userAction.action?methodName=add", { book_category_name: $("#book_category_name").val(), ///角色名 /* booktypename: $("input[ name='booktypename1']").val(), *///角色名 }, function (data) { /*根據後臺返回的參數來進行判斷 */ if (data==1) { layer.alert('添加成功', {icon: 1, title: '提示'}, function (i) { layer.close(i); layer.close(index);//關閉彈出層 $("#booktype")[0].reset()//重置form }) table.reload('testReload', {//重載表格 page: { curr: 1 // 從新從第 1 頁開始 } }) } else if(data==2){ layer.msg('添加失敗,請勿重複添加書本類別名稱') } }) }, cancel: function (index, layero) {//取消 $("#booktype")[0].reset()//重置form 根據id layer.close(index) } }); } } $('.layui-form .layui-btn').on('click', function () { var type = $(this).data('type'); active[type] ? active[type].call(this) : ''; }); /*表格 行內操做(編輯 以及 刪除 按鈕操做) */ table.on('tool(test)', function(obj){ var data = obj.data; //得到當前行數據 var urlex=document.getElementById("sj").value; var tr=obj.tr//活動當前行tr 的 DOM對象 console.log(data); var layEvent = obj.event; //得到 lay-event 對應的值(也能夠是表頭的 event 參數對應的值) if(layEvent === 'del'){ //刪除 layer.confirm('肯定刪除嗎?',{title:'刪除'}, function(index){ //向服務端發送刪除指令og $.getJSON(urlex+'/userAction.action?methodName=remove',{book_category_id:data.book_category_id}, function(ret){ layer.close(index);//關閉彈窗 table.reload('testReload', {//重載表格 page: { curr: 1 // 從新從第 1 頁開始 } }) }); layer.close(index); }); } else if(layEvent === 'edit'){ //編輯 layer.open({ type: 1 //Page層類型 ,skin: 'layui-layer-molv' ,area: ['380px', '270px'] ,title: ['編輯書本類別信息','font-size:18px'] ,btn: ['肯定', '取消'] ,shadeClose: true ,shade: 0 //遮罩透明度 ,maxmin: true //容許全屏最小化 ,content:$('#box1') //彈窗id ,success:function(layero,index){ console.info(data.book_category_id); $('#book_category_id').val(data.book_category_id); $('#book_category_name').val(data.book_category_name); },yes:function(index,layero){ /* $.ajaxSettings.async = false; */ $.getJSON(urlex+'/userAction.action?methodName=edit',{ book_category_name: $('#book_category_name').val(), book_category_id: data.book_category_id, },function(data){ //根據後臺返回的參數,來進行判斷 if(data>0){ layer.alert('編輯成功',{icon:1,title:'提示'},function(i){ layer.close(i); layer.close(index);//關閉彈出層 $("#booktype")[0].reset()//重置form }) table.reload('testReload',{//重載表格 page:{ curr:1 } }) } }); } }); } }); }); })
書本的類別後臺
manageDao(我把這個寫在了userdao裏面)
package com.chenjiahao.dao; import java.util.List; import java.util.Map; import org.w3c.dom.ls.LSInput; import com.chenjiahao.util.JsonBaseDao; import com.chenjiahao.util.JsonUtils; import com.chenjiahao.util.PageBean; import com.chenjiahao.util.StringUtils; public class UserDao extends JsonBaseDao { /** * 查詢類別表的數據 * * @param map * @param pageBean * @return * @throws Exception */ public List<Map<String, Object>> listCategory(Map<String, String[]> map, PageBean pageBean) throws Exception { String sql = "SELECT *FROM t_book_category WHERE TRUE"; String uname = JsonUtils.getParamVal(map, "uname"); if (StringUtils.isNotBlank(uname)) { sql = sql + " and book_category_name like '%" + uname.trim() + "%'"; } return super.executeQuery(sql, pageBean); } /** * 編輯類別 * * @param paMap * @return * @throws Exception */ public int edit(Map<String, String[]> paMap) throws Exception { String sql = "UPDATE t_book_category SET book_category_name=? WHERE book_category_id=?"; return super.executeUpdate(sql, new String[] { "book_category_name", "book_category_id" }, paMap); } /** * 新增類別 * * @param paMap * @return * @throws Exception */ public int add(Map<String, String[]> paMap) throws Exception { String sql = "INSERT INTO t_book_category(book_category_name) VALUES(?)"; return super.executeUpdate(sql, new String[] { "book_category_name" }, paMap); } /** * 刪除類別 * * @param paMap * @return * @throws Exception */ public int remove(Map<String, String[]> paMap) throws Exception { String sql = "DELETE FROM t_book_category WHERE book_category_id=?"; return super.executeUpdate(sql, new String[] { "book_category_id" }, paMap); } }
書本類別請求層:(UserAction)
/** * 查詢類別表的數據 * @param request * @param response * @return * @throws Exception */ public String listcartegory(HttpServletRequest request, HttpServletResponse response) throws Exception { PageBean pageBean = new PageBean(); pageBean.setRequest(request); List<Map<String, Object>> list = this.userDao.listCategory(request.getParameterMap(), pageBean); ObjectMapper om = new ObjectMapper(); Map<String, Object> map = new HashMap<>(); map.put("code", 0); map.put("count", pageBean.getTotal()); map.put("data", list); ResponseUtil.write(response, om.writeValueAsString(map)); return null; } /** * 類別編輯 * @param request * @param response * @return * @throws Exception */ public String edit(HttpServletRequest request, HttpServletResponse response) throws Exception { int add = this.userDao.edit(request.getParameterMap()); ObjectMapper om = new ObjectMapper(); ResponseUtil.write(response, om.writeValueAsString(add)); return null; } /** * 類別新增 * @param request * @param response * @return * @throws Exception */ public String add(HttpServletRequest request, HttpServletResponse response) throws Exception { int add = this.userDao.add(request.getParameterMap()); ObjectMapper om = new ObjectMapper(); ResponseUtil.write(response, om.writeValueAsString(add)); return null; } /** * 類別刪除 * @param request * @param response * @return * @throws Exception */ public String remove(HttpServletRequest request, HttpServletResponse response) throws Exception { int remove = this.userDao.remove(request.getParameterMap()); ObjectMapper om = new ObjectMapper(); ResponseUtil.write(response, om.writeValueAsString(remove)); return null; }
mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <config> <!-- <action path="/regAction" type="test.RegAction"> <forward name="failed" path="/reg.jsp" redirect="false" /> <forward name="success" path="/login.jsp" redirect="true" /> </action> --> <action path="/menuAction" type="com.chenjiahao.web.MenuAction"> <forward name="index" path="/index.jsp" redirect="false" /> </action> <action path="/userAction" type="com.chenjiahao.web.UserAction"> <forward name="index" path="/index.jsp" redirect="false" /> </action> <action path="/BookAction" type="com.chenjiahao.web.BookAction"> <forward name="index" path="/index.jsp" redirect="false" /> </action> <action path="/ControlActione" type="com.chenjiahao.web.ControlActione"> <forward name="index" path="/index.jsp" redirect="false" /> </action> </config>
展現:
不一樣用戶登陸進去看不同的tree:
數據操做: