②UserDao编写
package com.xw.dao; import java.util.List; import java.util.Map; import com.xw.entity.User; import com.zking.util.BaseDao; import com.zking.util.PageBean; import com.zking.util.StringUtils; /** * 用户 * * @author 索隆 * */ public class UserDao extends BaseDao<User> { // 分页模糊查询 public List<User> list(User user, PageBean pageBean) throws Exception { // sql语句编写 String sql = "select * from t_oa_user where 1=1"; // 获取参数 long id = user.getId(); String name = user.getName(); // 进行参数非空判断 if (StringUtils.isNotBlank(name)) { sql += " and name like '%" + name + "%'"; } // 如果bid不等于0说明传递过来了bid,此时的bid是有值的 if (id != 0) { sql += "and id=" + id; } return super.executeQuery(sql, User.class, pageBean); } // 新增 public int add(User User) throws Exception { int n=0; // sql语句编写 String sql = "insert into t_oa_user (name,loginName,pwd)values(?,?,?)"; n = super.executeUpdate(sql, User, new String[] { "name", "loginName", "pwd" }); return n; } // 删除 public int del(User User) throws Exception { // sql语句编写 String sql = "delete from t_oa_user where id=?"; return super.executeUpdate(sql, User, new String[] { "id" }); } // 修改 public int edit(User User) throws Exception { // sql语句编写 String sql = "update t_oa_user set name=?,loginName=?,pwd=? where id=?"; return super.executeUpdate(sql, User, new String[] { "name", "loginName", "pwd", "id" }); } // 登录校验 public User login(User User) throws Exception { // sql语句编写 String sql = "select * from t_oa_user where loginName='" + User.getLoginName() + "' and pwd='" + User.getPwd()+ "' "; List<User> list = super.executeQuery(sql, User.class, null); if (list != null && list.size() == 1) { return list.get(0); } else { return null; } } //不包含原表字段的分页模糊查询 public List<Map<String, Object>> userRole(User user, PageBean pageBean) throws Exception { // sql语句编写 String sql = "select u.*,\r\n" + "(CASE \r\n" + " WHEN u.rid='1' THEN '管理员'\r\n" + " WHEN u.rid='2' THEN '发起者'\r\n" + " WHEN u.rid='3' THEN '审批者'\r\n" + " WHEN u.rid='4' THEN '参与者'\r\n" + " WHEN u.rid='5' THEN '会议室管理员'\r\n" + "\r\n" + " ELSE\r\n" + " '其他'\r\n" + "END ) rname\r\n" + "from 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); } }
注意:这里的返回就是已经重构的executeQuery不要搞混了哦!!
3.Servlet编写
①R工具类的介绍
我们可以查看官网的表格内容显示的JSON格式是什么样子的,发现有以上几个属性:
code,msg,count,data
- code:只能填写“0”(别人的Layui规则)
- mag:没实际含义,可随意填写
- count:查询到的条数
- data:实体内容
我们想要在页面显示数据,那么就必须要满足它的JSON格式,我们就可以利用R工具类来简化我们的代码,不然每次遇到这种场景就需要手动创建Map集合然后.put添加属性的方式造数据。
package com.zking.util; import java.util.HashMap; 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; } }
这里也重构了和多次ok的方法,方便我们利用于不同的场景。
②Useraction编写
package com.xw.web; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.xw.entity.User; import com.xw.dao.UserDao; 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> { User user = new User(); UserDao userdao = new UserDao(); /** * 登录验证 * * @param req * @param resp * @throws Exception */ public void login(HttpServletRequest req, HttpServletResponse resp) throws Exception { User login = userdao.login(user); // 保存域对象 if (login != null) { HttpSession session = req.getSession(); session.setAttribute("user", login); } ResponseUtil.writeJson(resp, login); } /** * 注册新增用户 * * @param req * @param resp * @throws Exception */ public void register(HttpServletRequest req, HttpServletResponse resp) throws Exception { int i = userdao.add(user); if (i > 0) { ResponseUtil.writeJson(resp, i); } else { ResponseUtil.writeJson(resp, null); } } /**带分类管理的模糊查询 * @param req * @param resp * @throws Exception */ public void UserRole(HttpServletRequest req, HttpServletResponse resp) throws Exception { // 初始化pageBean PageBean pageBean = new PageBean(); pageBean.setRequest(req); //调用带分页查询的方法 List<Map<String, Object>> userRole = userdao.userRole(user, pageBean); //利用R工具类制造出符合要求的json格式数据 ResponseUtil.writeJson(resp, R.ok(0, "查询成功", pageBean.getTotal(), userRole)); } /**删除用户 * @param req * @param resp * @throws Exception */ public void del(HttpServletRequest req, HttpServletResponse resp) throws Exception { //调用删除的方法 int del = userdao.del(user); //利用R工具类制造出符合要求的json格式数据 ResponseUtil.writeJson(resp, R.ok(0, "删除成功")); } /**修改用户 * @param req * @param resp * @throws Exception */ public void edit(HttpServletRequest req, HttpServletResponse resp) throws Exception { //调用修改的方法 int del = userdao.edit(user); //利用R工具类制造出符合要求的json格式数据 ResponseUtil.writeJson(resp, R.ok(0, "修改成功")); } /**新增用户 * @param req * @param resp * @throws Exception */ public void add(HttpServletRequest req, HttpServletResponse resp) throws Exception { //调用新增的方法 int del = userdao.add(user); //利用R工具类制造出符合要求的json格式数据 ResponseUtil.writeJson(resp, R.ok(0, "新增成功")); } @Override public User getModel() { return user; } }
4.jsp页面搭建
一定要注意我们的层级结构
①userManage.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="/common/static.jsp"%> <!DOCTYPE> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>用户管理</title> <script type="text/javascript" src="static/js/system/userManage.js"></script> </head> <body> <!-- 搜索栏 --> <div class="layui-form-item"> <div class="layui-inline"> <label class="layui-form-label">用户名:</label> <div class="layui-input-inline"> <input type="text" id="name" placeholder="请输入用户名" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-inline"> <div class="layui-input-inline"> <button id="btn_search" type="button" class="layui-btn layui-btn-normal"> <i class="layui-icon layui-icon-search"></i> 查询 </button> <button id="btn_add" type="button" class="layui-btn">新增</button> </div> </div> </div> <table class="layui-hide" id="test" lay-filter="test"></table> <script type="text/html" id="barDemo"> <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a> <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a> </script> <script> </script> </body> </html>
②userEdit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="/common/static.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>
将JSP页面的逻辑代码分离
③userManage.js
var table,$,layer; var row; layui.use(['table','jquery','layer'], function(){ table = layui.table ,layer=layui.layer ,$=layui.jquery; initTable(); //为查询按钮设置点击事件 $("#btn_search").click(function(){ query(); }) //为新增按钮设置点击事件 $("#btn_add").click(function(){ row=null; edit('新增'); }) }); //新增/修改的点击事件 function edit(title){ layer.open({ type: 2, //layer提供了5种层类型。可传入的值有:0(信息框,默认)1(页面层)2(iframe层)3(加载层)4(tips层) title:title, area: ['660px', '340px'], //宽高 skin: 'layui-layer-rim', //样式类名 content: 'jsp/system/userEdit.jsp', //书本编辑页面 btn:['保存','关闭'], yes: function(index, layero){ //调用子页面中提供的getData方法,快速获取子页面的form表单数据 let data= $(layero).find("iframe")[0].contentWindow.getData(); console.log(data); //判断title标题 let methodName="add"; if(title=="编辑") methodName="edit"; $.post('user.action?methodName='+methodName, data,function(rs){ if(rs.success){ //关闭对话框 layer.closeAll(); //调用查询方法刷新数据 query(); }else{ layer.msg(rs.msg,function(){}); } },'json'); }, btn2: function(index, layero){ layer.closeAll(); } }); } //查询的点击事件 function query(){ //表格的重载 table.reload('test', { where: { //设定异步数据接口的额外参数,任意设 name: $("#name").val() } //默认limit需要改成我们自己工具类的名字 ,request: { pageName: 'page ' //页码的参数名称,默认:page ,limitName: 'rows' //每页数据量的参数名,默认:limit } }); //只重载数据 } //将分页查询方法封装 function initTable(){ table.render({ elem: '#test' ,url:'user.action?methodName=UserRole' ,toolbar: '#toolbarDemo' //开启头部工具栏,并为其绑定左侧模板 ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可 title: '提示' ,layEvent: 'LAYTABLE_TIPS' ,icon: 'layui-icon-tips' }] ,title: '用户数据表' ,cols: [[ {type: 'checkbox', fixed: 'left'} ,{field:'id', title:'ID', width:80, fixed: 'left', unresize: true, sort: true} ,{field:'loginName', title:'账户名', width:120, edit: 'text'} ,{field:'name', title:'真实姓名', width:150, edit: 'text', templet: function(res){ return '<em>'+ res.name +'</em>' }} ,{field:'pwd', title:'密码', width:80, edit: 'text', sort: true} ,{field:'rname', title:'身份', width:100} ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150} ]] ,page: true }); //监听行工具事件 table.on('tool(test)', function(obj){ row = obj.data; if(obj.event === 'del'){ layer.confirm('确认删除吗?', {icon: 3, title:'提示'}, function(index){ $.post('user.action',{ 'methodName':'del', 'id':row.id },function(rs){ if(rs.success){ //调用查询方法刷新数据 query(); }else{ layer.msg(rs.msg,function(){}); } },'json'); layer.close(index); }); } else if(obj.event === 'edit'){ edit('编辑'); } }); }
④userEdit.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'); }
5.案例效果演示
①查询
②新增
③修改
④删除
到这里我的分享就结束了,欢迎到评论区探讨交流!!
如果觉得有用的话还请点个赞吧 ♥ ♥