前言
在我前几篇的文章中,已经如何实现属性菜单及选项卡的使用,接下来就带大家去实现在layui框架界面实现增删改查(针对用户进行)
一,相关的配置准备
了解layui官网的框架,方便在后面使用并提高效率, 在Laui旧官网的复制相对应的展示的后台界面
1.1 在页面前端显示的总的数据 ,需要更加规范,所以我们在数据库中就已经编写相对应的字段名转文字显示,也就是将表中的name字段内容显示为中文
SELECT u.*, (CASE WHEN u.rid = '1' THEN '管理员' WHEN u.rid = '2' THEN '发起者' WHEN u.rid = '3' THEN '审批员' WHEN u.rid = '4' THEN '参与者' WHEN u.rid = '5' THEN '会议管理员' ELSE '其他' END ) rname FROM `t_oa_user` u
如上图所示在数据展示的时候,就知道它所的职位与权限是什么。
1.1,编写Userdao,来进行具体数据需要什么操作,到时在servlet调用相对应的方法即可,
会发现在查询语句中正是我们在数据库编译的sql语句
/** * 带模糊查询方法 * **/ public List<Map<String, Object>> userRole(User user, PageBean pageBean) throws Exception { String sql = "SELECT\r\n" + " u.*,\r\n" + " (\r\n" + "CASE\r\n" + " WHEN u.rid = '1' THEN\r\n" + " '管理员' \r\n" + " WHEN u.rid = '2' THEN\r\n" + " '发起者' \r\n" + " WHEN u.rid = '3' THEN\r\n" + " '审批员' \r\n" + " WHEN u.rid = '4' THEN\r\n" + " '参与者' \r\n" + " WHEN u.rid = '5' THEN\r\n" + " '会议管理员' ELSE '其他' \r\n" + "END \r\n" + " ) rname \r\n" + "FROM\r\n" + " `t_oa_user` u where 1=1"; String name = user.getName(); if (StringUtils.isNotBlank(name)) sql += " and name like '%" + name + "%'"; return super.executeQuery(sql, pageBean); } public int add(User user) throws Exception { String sql = "insert into t_oa_user(name,loginName,pwd) values(?,?,?)"; return super.executeUpdate(sql, user, new String[] {"name","loginName","pwd"}); } public int del(User user) throws Exception { String sql = "delete from t_oa_user where id = ?"; return super.executeUpdate(sql, user, new String[] {"id"}); } public int edit(User user) throws Exception { String sql = "update t_oa_user set name = ?,loginName = ?,pwd = ? where id = ?"; return super.executeUpdate(sql, user, new String[] {"name","loginName","pwd","id"}); }
2.1 后端servlet编写,这时候要用到一个R工具类,要用Layui框架就必须遵循它的回显数据原则,R这个工具类包含了显现数据格式化,这样在后端就不要参数要赋值的情况
R工具类:
package com.zking.util; import java.util.HashMap; /** * * @author 兵 * */ public class R extends HashMap{ public R data(String key, Object value) { this.put(key, value); return this; } public static R ok(int code, String msg) { R r = new R(); r.data("success", true).data("code", code).data("msg", msg); return r; } public static R error(int code, String msg) { R r = new R(); r.data("success", false).data("code", code).data("msg", msg); return r; } public static R ok(int code, String msg,Object data) { R r = new R(); r.data("success", true).data("code", code).data("msg", msg).data("data", data); return r; } public static R ok(int code, String msg, long count, Object data) { R r = new R(); r.data("success", true).data("code", code).data("msg", msg).data("count", count).data("data", data); return r; } }
servlet代码:
package com.zking.web; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.zking.dao.UserDao; import com.zking.entity.User; import com.zking.framework.ActionSupport; import com.zking.framework.ModelDriver; import com.zking.util.PageBean; import com.zking.util.R; import com.zking.util.ResponseUtil; public class UserAction extends ActionSupport implements ModelDriver<User> { private User user = new User();//实体 private UserDao userdao = new UserDao();//方法 public void login(HttpServletRequest req, HttpServletResponse resp) { try { //调用方法 User u = userdao.login(user); //继承中ModelDriver已经封装依懒mvc中req接受前端传来的值,当前结果保存到该方法中 ResponseUtil.writeJson(resp, u); } catch (Exception e) { e.printStackTrace(); } } public void UserRole(HttpServletRequest req, HttpServletResponse resp) { try { PageBean pageBean =new PageBean(); pageBean.setRequest(req); //调用方法 List<Map<String, Object>> userRole = userdao.userRole(user, pageBean); ResponseUtil.writeJson(resp, R.ok(0, "查询成功", pageBean.getTotal(), userRole )); } catch (Exception e) { e.printStackTrace(); } } public void add(HttpServletRequest req, HttpServletResponse resp) { try { //调用方法 int add=userdao.add(user); ResponseUtil.writeJson(resp, R.ok(0, "新增成功")); } catch (Exception e) { e.printStackTrace(); } } public void del(HttpServletRequest req, HttpServletResponse resp) { try { //调用方法 int del=userdao.del(user); ResponseUtil.writeJson(resp, R.ok(0, "删除成功")); } catch (Exception e) { e.printStackTrace(); } } public void edit(HttpServletRequest req, HttpServletResponse resp) { try { //调用方法 int edit=userdao.edit(user); ResponseUtil.writeJson(resp, R.ok(0, "修改成功")); } catch (Exception e) { e.printStackTrace(); } } //注册 public void register(HttpServletRequest req, HttpServletResponse resp) { try { int register = userdao.register(user); //判断前端的值大于0 证明有值 if (register > 0) { //回显ok 代表成功 ResponseUtil.writeJson(resp, "OK"); } else { //回显失败 代表失败 ResponseUtil.writeJson(resp, "NO"); } } catch (Exception e) { e.printStackTrace(); } } @Override public User getModel() { return user; } }
显然代码发现,在实现后端servlet的时候,我们使用R工具类,来帮助我们来回显前端需要的数据
前端jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <%@include file="/common/header.jsp"%> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>后台的主界面</title> <!-- 引入 layui.js --> <script src="static/js/index.js"></script> <style type="text/css"> .layui-tab-item{ height: 100%; } </style> </head> <body> <div class="layui-layout layui-layout-admin"> <div class="layui-header"> <div class="layui-logo layui-hide-xs layui-bg-black">layout demo</div> <!-- 个人头像及账号操作 --> <ul class="layui-nav layui-layout-right"> <li class="layui-nav-item layui-hide layui-show-md-inline-block"> <a href="javascript:;"><img src="static/images/20200108151634_M44Az.jpeg" class="layui-nav-img"> 操作 </a> <dl class="layui-nav-child"> <dd> <a href="javascript:;">${user.name }</a> </dd> <dd> <a href="login.jsp">退出</a> </dd> </dl> </li> </ul> </div> <div class="layui-side layui-bg-black"> <div class="layui-side-scroll"> <ul id="menu" class="layui-nav layui-nav-tree" lay-filter="menu"> </ul> </div> </div> <div class="layui-body" style="height: 100%;"> <div class="layui-tab" lay-filter="demo" style="height: 100%;" lay-allowclose="true"> <ul class="layui-tab-title"> <li class="layui-this" lay-id="11">网站设置</li> </ul> <div class="layui-tab-content" style="height: 100%;"> <div class="layui-tab-item layui-show">内容1</div> </div> </div> </div> <div class="layui-footer"> <!-- 底部固定区域 --> </div> </div> </body> </html>
2.2 我们已经将jsp界面代码与实现的代码实现分离封装js这样我们在jsp引入即可(是Layui的官网copy相对应的代码)需要根据自身代码修改一点内容
封装的js代码:
//将所需要的模块定义在此 用的时候赋值即可 var element,layer,util,$; layui.use(['element', 'layer', 'util'], function(){ element = layui.element ,layer = layui.layer ,util = layui.util ,$ = layui.$; $.ajax({ url:"permission.action?methodName=menus", dataType:'json', success:function(data){ console.log(data); var htmlStr=''; $.each(data,function(i,n){ //拼接一级菜单 开始标签 htmlStr +='<li class="layui-nav-item layui-nav-itemed">'; htmlStr +=' <a class="" href="javascript:;">'+n.text+'</a>'; if(n.hasChildren){//判断是否有子标签 var children=n.children//得到子标签的列表 htmlStr +='<dl class="layui-nav-child">';//拼接子标签 开始标签 $.each(children,function(index,nodel){//遍历子标签 htmlStr += '<dd><a href="javascript:;" onclick="opentab(\''+nodel.text+'\',\''+nodel.attributes.self.url+'\',\''+nodel.id+'\')">'+nodel.text+'</a></dd>' console.log(nodel.attributes.self.url) }) htmlStr +='</dl>';//拼接子标签 结束标签 } htmlStr +='</li>'; //拼接一级菜单 结束标签 }) $("#menu").html(htmlStr); element.render('menu');//渲染 } }) }); //给子菜单添加函数接口 点击菜单生成相对应的选项卡 function opentab(title,content,id){//参数是二级菜单 var $nodel=$('li[lay-id="'+id+'"]') if($nodel.length==0){//当选项卡的长度为0时,不再打开重复的选项卡 element.tabAdd('demo', { title: title//在选项卡展示的标题 ,content: "<iframe frameborder='0' src='"+content+"' style='height: 100%;width: 100%' scrolling='auto'></iframe> " //二级菜单text内容 ,id: id //二级菜单id }) } element.tabChange("demo",id);//点击左侧二级菜单右侧选项卡同步选上 }
2.3 在我们实现增加与修改,需要弹出一个页面来实现将数据显示前端(共用一个页面),所以我们来编写这个页面
增加修改jsp页面代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@include file="/common/header.jsp"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="static/js/system/userEdit.js"></script> <title>用户新增</title> </head> <style> .layui-form-select dl{ max-height:150px; } </style> <body> <div style="padding:10px;"> <form class="layui-form layui-form-pane" lay-filter="user"> <input type="hidden" name="id"/> <div class="layui-form-item"> <label class="layui-form-label">用户名称</label> <div class="layui-input-block"> <input type="text" id="name" name="name" autocomplete="off" placeholder="请输入用户名" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">用户角色</label> <div class="layui-input-block"> <select name="rid"> <option value="">---请选择---</option> <option value="1">管理员</option> <option value="2">发起者</option> <option value="3">审批者</option> <option value="4">参与者</option> <option value="5">会议管理员</option> </select> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">登录账号</label> <div class="layui-input-block"> <input type="text" name="loginName" lay-verify="required" placeholder="请输入账号" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">登录密码</label> <div class="layui-input-block"> <input type="password" name="pwd" placeholder="请输入密码" autocomplete="off" class="layui-input"> </div> </div> </form> </div> </body> </html>
在进行修改的时候我们需要赋值给修改页面赋值内容,所以再编写一个Edit修改js来进行页面赋值内容,在jsp引入Edit引入。
Edit js:
let layer,form,$; layui.use(['layer','form','jquery'],function(){ layer=layui.layer,form=layui.form,$=layui.jquery; initData(); }); function initData(){ console.log(parent.row); if(null!=parent.row){ //因为layui.each内部的逻辑问题导致的所以要先深拷贝一份然后再去val //parent.row:表格行对象 form.val('user',$.extend({}, parent.row||{})); $('#name').attr('readonly','readonly'); } } function getData(){ return form.val('user'); }
最后增删改查运行结果: