文章目录
- 前言
- 一、后台代码编写
- 1.1 数据表优化
- 1.2 R工具类
- 1.3 UserDao新增改查
- 1.4 Servlet的编写
- 二、前台页面的编写
- 2.1 userManege.jsp
- 2.2 userManage.js
- 2.3 新增、修改用户共用jsp
- 2.4add、edit的js
- 三、演示
- 3.1 查询
- 3.2 新增
- 3.3 修改
- 3.4 删除
前言
在上篇博客我们实现了左侧树形菜单与选项卡,今天我们来实现最重要的部分——数据表格的增删改查
一、后台代码编写
1.1 数据表优化
将rid身份用中文表示,即将 rid 转换为对应的角色名称
SELECTu.*,CASEWHEN 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 AS rname
FROMt_oa_user u;
1.2 R工具类
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;}/*** data 数据传入 code返回结果成功还是失败 count分页* @param code* @param msg* @return*/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;}
}
-
data方法:该方法用于向R对象中添加键值对数据,并返回R对象本身,以支持链式调用
-
ok方法和error方法:这些方法用于返回通用格式的响应结果。
-
分页信息:代码中提供了一个构建分页响应结果的方法ok,其中包含了count和data两个部分。
1.3 UserDao新增改查
package com.xqx.dao;import java.util.List;
import java.util.Map;import com.xqx.entity.User;
import com.zking.util.BaseDao;
import com.zking.util.MD5;
import com.zking.util.PageBean;
import com.zking.util.StringUtils;/*** @author W许潜行 2023年7月11日 上午11:20:43*/
public class UserDao extends BaseDao<User> {/*** 查询所有用户* * @param user* @param clz* @param pageBean* @return* @throws Exception*/public List<User> list(User user, Class<User> clz, PageBean pageBean) throws Exception {String sql = "select * from t_oa_user where 1=1";return super.executeQuery(sql, clz, pageBean);}/*** 查询所有用户角色* * @param user* @param pageBean* @return* @throws Exception*/public List<Map<String, Object>> userRoles(User user, PageBean pageBean) throws Exception {String sql = "SELECT\r\n" +" 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" +" ELSE '其他'\r\n" +" END AS rname\r\n" +"FROM\r\n" +" t_oa_user u";// 按照登录账号模糊查询if (StringUtils.isNotBlank(user.getLoginName())) {sql += " WHERE loginName LIKE '" + user.getLoginName() + "%'";}return super.executeQuery(sql, pageBean);}/*** 新增用户* * @param user* @throws Exception*/public int addUser(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" });}/*** 编辑用户* * @param user* @throws Exception*/public int editUser(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" });}/*** 删除用户* * @param user* @throws Exception*/public int delUser(User user) throws Exception {String sql = "delete from t_oa_user where id=?";return super.executeUpdate(sql, user, new String[] { "id" });}/*** 登录* * @param user* @return* @throws Exception*/public User login(User user) throws Exception {String sql = "select * from t_oa_user where loginName='" + user.getLoginName() + "'and pwd='" + user.getPwd()+ "'";List<User> userList = super.executeQuery(sql, User.class, null);if (userList.size() == 1) {return userList.get(0);}return null;}/*** 注册* * @param user* @return* @throws Exception*/public int register(User user) throws Exception {String sql = "insert into t_oa_user(name,loginName,pwd,rid) values(?,?,?,4)";return super.executeUpdate(sql, user, new String[] { "name", "loginName", "pwd" });}
}
1.4 Servlet的编写
package com.xqx.web;import java.io.IOException;
import java.util.List;
import java.util.Map;import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.xqx.dao.UserDao;
import com.xqx.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;/*** @author W许潜行 2023年7月11日 上午11:20:35*/
public class UserAction extends ActionSupport implements ModelDriver<User> {User user = new User();UserDao ud = new UserDao();R R = new R();public void login(HttpServletRequest req, HttpServletResponse resp) {try {User login = ud.login(user);ResponseUtil.writeJson(resp, login);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void register(HttpServletRequest req, HttpServletResponse resp) {try {int register = ud.register(user);ResponseUtil.writeJson(resp, register);} catch (Exception e) {e.printStackTrace();}}/*** * @param req* @param resp* @throws IOException* @throws ServletException*/public void userRoles(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {try {PageBean pageBean = new PageBean();pageBean.setRequest(req);List<Map<String, Object>> list = ud.userRoles(user, pageBean);ResponseUtil.writeJson(resp, R.ok(0, "查询成功", pageBean.getTotal(), list));} catch (Exception e) {e.printStackTrace();}}/*** 用户新增* * @param req* @param resp* @return* @throws IOException* @throws ServletException*/public void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {try {int addUser = ud.addUser(user);if (addUser > 0) {ResponseUtil.writeJson(resp, R.ok(200, "用户新增成功"));} else {ResponseUtil.writeJson(resp, R.error(0, "用户新增失败"));}ResponseUtil.writeJson(resp, addUser);} catch (Exception e) {e.printStackTrace();}}/*** 用户编辑* * @param req* @param resp* @throws IOException* @throws ServletException*/public void editUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {try {int editUser = ud.editUser(user);if (editUser > 0) {ResponseUtil.writeJson(resp, R.ok(200, "用户编辑成功"));} else {ResponseUtil.writeJson(resp, R.error(0, "用户编辑失败"));}ResponseUtil.writeJson(resp, editUser);} catch (Exception e) {e.printStackTrace();}}/*** 用户删除* * @param req* @param resp* @throws IOException* @throws ServletException*/public void delUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {try {int delUser = ud.delUser(user);if (delUser > 0) {ResponseUtil.writeJson(resp, R.ok(200, "用户删除成功"));} else {ResponseUtil.writeJson(resp, R.error(0, "用户删除失败"));}ResponseUtil.writeJson(resp, delUser);} catch (Exception e) {e.printStackTrace();}}@Overridepublic User getModel() {// TODO Auto-generated method stubreturn user;}}
二、前台页面的编写
2.1 userManege.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<%@ include file="../../common/head.jsp"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">.layui-tab{
height: 100%;
}
</style>
</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 id="tb" lay-filter="tb" class="layui-table" style="margin-top:-15px;"></table><!-- 对话框(新增和编辑共用一个页面) -->
<table class="layui-hide" id="test" lay-filter="test"></table><script type="text/html" id="toolbarDemo"><div class="layui-btn-container"><button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button><button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button><button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button></div>
</script><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 type="text/javascript" src="static/js/system/userManage.js"></script></body>
</html>
2.2 userManage.js
let layer, $, table;
var row;
layui.use([ 'jquery', 'layer', 'table' ], function() {layer = layui.layer, $ = layui.jquery, table = layui.table;// 初始化数据表格initTable();// 绑定查询按钮的点击事件$('#btn_search').click(function() {query();});// 绑定新增按钮的点击事件$('#btn_add').click(function() {row = null;open('新增');});
});// 1.初始化数据表格
function initTable() {table.render({elem : '#tb',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(tb)', function(obj) {//给行数据赋值row = obj.data;if (obj.event == "edit") {open("编辑");} else 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 {}});}// 2.点击查询
function query() {//表格重载table.reload('tb', {url : $("#ctx").val() + '/user.action', // 请求地址method : 'POST', // 请求方式,GET或者POSTloading : true, // 是否显示加载条(默认 true)page : true, // 是否分页where : { // 设定异步数据接口的额外参数,任意设'methodName' : 'userRole','name' : $('#name').val()},request : { // 自定义分页请求参数名pageName : 'page', // 页码的参数名称,默认:pagelimitName : 'rows' // 每页数据量的参数名,默认:limit}});
}// 3.对话框
function open(title) {layer.open({type : 2, // layer提供了5种层类型。可传入的值有:0(信息框,默认)1(页面层)2(iframe层)3(加载层)4(tips层)title : title,area : [ '660px', '340px' ], // 宽高skin : 'layui-layer-rim', // 样式类名content : $("#ctx").val() + '/jsp/system/userEdit.jsp', // 书本编辑页面btn : [ '保存', '关闭' ],yes : function(index, layero) {// 调用子页面中提供的getData方法,快速获取子页面的form表单数据 getData()子页面的方法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();}});
}
2.3 新增、修改用户共用jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%@include file="/common/head.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath }/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>
2.4add、edit的js
let layer,form,$;
layui.use(['layer','form','jquery'],function(){layer=layui.layer,form=layui.form,$=layui.jquery;initData();
});function initData(){if(null!=parent.row){//parent.row:表格行对象form.val('user',$.extend({}, parent.row||{}));$('#name').attr('readonly','readonly');}
}function getData(){return form.val('user');
}
三、演示
3.1 查询
3.2 新增
3.3 修改