用layui完成 tree/权限(二星)/增删改查
写一个简单的登录界面(根据用户的id来获取相对应的权限)
<%@ 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>
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>> 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)
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 文件的引用)
<%@ 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.js
$(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); } } } }); } }); })
MenuDao
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); } } }
MenuAction
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书本类别
<%@ 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, 300, title: '书籍类别序号', sort: true} ,{field:'book_category_name', height:80,300, title: '书籍类别名称'} ,{field:'right',height:80, 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:
数据操作: