话不多说,根据我前面的博客我们直接进行操作。
记住以下的文件放置,防止操作出不来.
这是我们要完成的界面及功能
后台功能实现
数据查看
- 我们在userDao方法里面进行增删改查的方法
- 我们在userAction进行方法的编写
- R工具类的介绍
查询
userDao方法
因为我们的数据库的rid需要转成权限名,我们sql就要写case函数进行编写sql
/*** List<User>、List<Map>都是转成json数组 查询结果携带rname* * @param user* @param pageBean* @return* @throws Exception*/public List<Map<String, Object>> userRole(User user, PageBean pageBean) throws Exception {String sql = "select u.*,\r\n" + "(case u.rid\r\n" + "when 1 then '管理员'\r\n" + "when 2 then '发起者'\r\n"+ "when 3 then '审批者'\r\n" + "when 4 then '参与者'\r\n" + "when 5 then '会议管理员'\r\n"+ "else '其他角色' end) as 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);}
userAction方法
因为我们用的是Layui的框架,所以我们要遵循他的规则来进行一个编写。
我们就用map集合进行保存。后面会用R工具类进行一个优化
public void userRole(HttpServletRequest req, HttpServletResponse resp) throws Exception {PageBean pageBean = new PageBean();pageBean.setRequest(req);List<Map<String, Object>> userRole = userDao.userRole(user, pageBean);Map<String, Object> map = new HashMap<String, Object>();map.put("code", "0");map.put("masg", "查询成功");map.put("count", pageBean.getTotal());map.put("data", userRole);ResponseUtil.writeJson(resp, map);ResponseUtil.writeJson(resp, map);}
R工具类的介绍
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;}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;}
}
我们在userAction查询的方法上进行一个R工具类的使用
public void userRole(HttpServletRequest req, HttpServletResponse resp) throws Exception {PageBean pageBean = new PageBean();pageBean.setRequest(req);List<Map<String, Object>> userRole = userDao.userRole(user, pageBean);// 利用R工具类ResponseUtil.writeJson(resp, R.ok(0, "查询成功", pageBean.getTotal(), userRole));}
这样我们就进行了一个代码的优化。后面的代码我们也可以用R工具类的优化
增加
userDao
/*** 增加用户* * @param user* @return* @throws Exception*/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" });}
userAction
public void add(HttpServletRequest req, HttpServletResponse resp) throws Exception {int i = userDao.add(user);// 利用R工具类ResponseUtil.writeJson(resp, R.ok(0, "新增成功"));}
修改
userDao
/*** 修改用户* * @param user* @return* @throws Exception*/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" });}
userAction
public void edit(HttpServletRequest req, HttpServletResponse resp) throws Exception {int i = userDao.edit(user);// 利用R工具类ResponseUtil.writeJson(resp, R.ok(0, "修改成功"));}
删除
userDao
/*** 删除用户* * @param user* @return* @throws Exception*/public int del(User user) throws Exception {String sql = "delete from t_oa_user where id = ?";return super.executeUpdate(sql, user, new String[] { "id" });}
userAction
public void del(HttpServletRequest req, HttpServletResponse resp) throws Exception {int i = userDao.del(user);// 利用R工具类ResponseUtil.writeJson(resp, R.ok(0, "删除成功"));}
后台完整代码
userDao
package com.zking.dao;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;import com.zking.entity.User;
import com.zking.util.BaseDao;
import com.zking.util.DBAccess;
import com.zking.util.PageBean;
import com.zking.util.StringUtils;/*** * @author tgq**/
public class UserDao extends BaseDao<User> {/*** 查询所有用户* * @param user* @param pageBean* @return* @throws Exception*/public List<User> list(User user, PageBean pageBean) throws Exception {String sql = "select * from t_oa_user where 1=1";return super.executeQuery(sql, User.class, pageBean);}/*** 获取实体类* * @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> list = super.executeQuery(sql, User.class, null);if (list != null && list.size() == 1) {return list.get(0);}return null;}/*** 获取用户最大id* * @return* @throws Exception*/public int getMaxId() throws Exception {// 创建连接Connection conn = DBAccess.getConnection();int id = 0;String sql = "select MAX(id) from t_oa_user";PreparedStatement ps = conn.prepareStatement(sql);ResultSet rs = ps.executeQuery();if (rs.next()) {id = rs.getInt(1);}return id;}/*** 注册* * @param user* @return* @throws Exception*/public int Register(User user) throws Exception {String sql = "insert into t_oa_user values(?,?,?,?,?)";return super.executeUpdate(sql, user, new String[] { "id", "name", "loginName", "pwd", "rid" });}/*** List<User>、List<Map>都是转成json数组 查询结果携带rname* * @param user* @param pageBean* @return* @throws Exception*/public List<Map<String, Object>> userRole(User user, PageBean pageBean) throws Exception {String sql = "select u.*,\r\n" + "(case u.rid\r\n" + "when 1 then '管理员'\r\n" + "when 2 then '发起者'\r\n"+ "when 3 then '审批者'\r\n" + "when 4 then '参与者'\r\n" + "when 5 then '会议管理员'\r\n"+ "else '其他角色' end) as 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);}/*** 增加用户* * @param user* @return* @throws Exception*/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" });}/*** 修改用户* * @param user* @return* @throws Exception*/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" });}/*** 删除用户* * @param user* @return* @throws Exception*/public int del(User user) throws Exception {String sql = "delete from t_oa_user where id = ?";return super.executeUpdate(sql, user, new String[] { "id" });}}
userAction
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();/*** 登录* * @param req* @param resp* @return* @throws Exception*/public void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {User u = userDao.login(user);ResponseUtil.writeJson(resp, u);}/*** 注册* * @param req* @param reps* @throws Exception*/public void Register(HttpServletRequest req, HttpServletResponse reps) throws Exception {String loginName = req.getParameter("loginName");String password = req.getParameter("password");// 先获取最大的id数int maxId = userDao.getMaxId();user = new User(maxId + 1, req.getParameter("name"), loginName, password,Long.parseLong(req.getParameter("rid")));int register = userDao.Register(user);ResponseUtil.writeJson(reps, register);}public void userRole(HttpServletRequest req, HttpServletResponse resp) throws Exception {PageBean pageBean = new PageBean();pageBean.setRequest(req);List<Map<String, Object>> userRole = userDao.userRole(user, pageBean);// Map<String, Object> map = new HashMap<String, Object>();// map.put("code", "0");// map.put("masg", "查询成功");// map.put("count", pageBean.getTotal());// map.put("data", userRole);// ResponseUtil.writeJson(resp, map);// 利用R工具类ResponseUtil.writeJson(resp, R.ok(0, "查询成功", pageBean.getTotal(), userRole));}public void add(HttpServletRequest req, HttpServletResponse resp) throws Exception {int i = userDao.add(user);// 利用R工具类ResponseUtil.writeJson(resp, R.ok(0, "新增成功"));}public void del(HttpServletRequest req, HttpServletResponse resp) throws Exception {int i = userDao.del(user);// 利用R工具类ResponseUtil.writeJson(resp, R.ok(0, "删除成功"));}public void edit(HttpServletRequest req, HttpServletResponse resp) throws Exception {int i = userDao.edit(user);// 利用R工具类ResponseUtil.writeJson(resp, R.ok(0, "修改成功"));}@Overridepublic User getModel() {return user;}}
前台功能实现
查询
jsp界面(userManage.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">
<title>用户管理</title>
<script 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="userTable" 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></body>
</html>
js(userManage.js)
记得我们在userManage.jsp里面导入
<script src="static/js/system/userManage.js"></script>
var table, $;
var row;
layui.use([ 'table', 'jquery' ], function() {table = layui.table;$ = layui.jquery;userinit();$("#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();}});}/*** 表格重载* * @returns*/
function query() {table.reload('userTable', {where : { // 设定异步数据接口的额外参数,任意设name : $("#name").val()},request : {pageName : 'page' // 页码的参数名称,默认:page,limitName : 'rows' // 每页数据量的参数名,默认:limit 我们的定义的是rows,所以更改为rows}}); // 只重载数据
}function userinit() {table.render({elem : '#userTable',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',fixed : 'left',unresize : true,sort : true}, {field : 'name',title : '用户名',edit : 'text'}, {field : 'loginName',title : '用户账号',edit : 'text'},{field : 'pwd',title : '密码',edit : 'text',}, {field : 'rname',title : '权限名',}, {fixed : 'right',title : '操作',toolbar : '#barDemo',width : 150} ] ],page : true});// 头工具栏事件table.on('toolbar(test)', function(obj) {var checkStatus = table.checkStatus(obj.config.id);switch (obj.event) {case 'getCheckData':var data = checkStatus.data;layer.alert(JSON.stringify(data));break;case 'getCheckLength':var data = checkStatus.data;layer.msg('选中了:' + data.length + ' 个');break;case 'isAll':layer.msg(checkStatus.isAll ? '全选' : '未全选');break;// 自定义头工具栏右侧图标 - 提示case 'LAYTABLE_TIPS':layer.alert('这是工具栏右侧自定义的一个图标按钮');break;};});// 监听行工具事件table.on('tool(test)', function(obj) {row = obj.data;// console.log(obj)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('编辑');}});
}
记住我们的userinit方法,这是一个把数据进行一个绑定的方法,做一个数据回显
运行效果
我么要编写一个数据重载的方法,并且在查询的按钮上设置一个点击事件还要调用重载的方法。
$("#btn_search").click(function() {query();});
/*** 表格重载* * @returns*/ function query() {table.reload('userTable', {where : { // 设定异步数据接口的额外参数,任意设name : $("#name").val()},request : {pageName : 'page' // 页码的参数名称,默认:page,limitName : 'rows' // 每页数据量的参数名,默认:limit 我们的定义的是rows,所以更改为rows}}); // 只重载数据 }
这样我们就可以进行搜索了
增加、修改
jsp界面(userEdit.js)
<%@ 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>
js(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');
}
我们要在userManage.js里面写一个增加和修改的方法
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();}});}
我么调用的都是userEdit.jsp的界面
在userManage.js监听事件里面我们进行调用edit的方法就行
// 监听行工具事件table.on('tool(test)', function(obj) {row = obj.data;// console.log(obj)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('编辑');}});
我们进行一个编辑
删除
我们在userManage.jsp里面的监听事件进行一个删除的提示和调用
// 监听行工具事件table.on('tool(test)', function(obj) {row = obj.data;// console.log(obj)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('编辑');}});
我们删除账户sa
删除之后会进行一个刷新
我们就删除完成了
分享就到这里,希望对您们有用!!!
后续我会加上源码!