目录
一、前期准备
1.数据表格
2.弹出层
3.用户表数据查询
二、用户管理后台编写
三、前端JS编写
四、效果展示
一、前期准备
1.数据表格
在layui官网找到我们需要的数据表格
根据需求复制修改代码,再找到表单复制一个输入框和按钮,做一个搜索功能
用户管理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 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>
2.弹出层
在数据显示页面上,我们做新增修改无非两种方法,一种是页面跳转,一种是以弹出层的方法显示
用户新增修改通用JSP页面---userEdit.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>
3.用户表数据查询
准备一张用户管理的数据表
因为rid分别代表着不同用户的权限,在数据显示时不可能去显示rid,所以需要给对应的值进行诠释
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
二、用户管理后台编写
UserDao类增删改查方法,同样是继承了basedao,basedao在这就不过多讲解了,有兴趣的可以看Lay UI入门
package com.ctb.dao;import java.util.List;
import java.util.Map;import com.ctb.entity.User;
import com.zking.util.BaseDao;
import com.zking.util.PageBean;
import com.zking.util.StringUtils;
/*** * @author biao** 2023年7月10日*/
public class UserDao extends BaseDao<User> {//查询所有public List<User> list( User user, PageBean pageBean) throws Exception {String sql="select * from t_oa_user";return super.executeQuery(sql, User.class, pageBean);}//用户管理查询public List<Map<String, Object>> listUserRole(User user, PageBean pageBean) throws Exception {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"+ " ELSE\r\n"+ " '其它'\r\n"+ "END) \r\n"+ " 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);}//登录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);}else {return null;}}//注册public int register(User user) throws Exception {String sql = "insert into t_oa_user(name,loginName,pwd,rid) values(?,?,?,0);";// 定义sql语句return super.executeUpdate(sql,user,new String[] {"name","loginName","pwd"});}//增加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 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"});}//删除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 static void main(String[] args) throws Exception {
// UserDao u = new UserDao();
// int register = u.register(new User(12, "彪", "ctb", "123", 0));
//
// System.out.println(register);
// }}
注:在用户查询中,因用户表没有rname这个字段或多表查询,在basedao中写了一个适合多表联查数据返回的方法
/*** 适合多表联查的数据返回* @param sql* @param pageBean* @return* @throws SQLException* @throws InstantiationException* @throws IllegalAccessException*/public List<Map<String, Object>> executeQuery(String sql, PageBean pageBean)throws SQLException, InstantiationException, IllegalAccessException {List<Map<String, Object>> list = new ArrayList<>();Connection con = DBAccess.getConnection();PreparedStatement pst = null;ResultSet rs = null;/** 是否需要分页? 无需分页(项目中的下拉框,查询条件教员下拉框,无须分页) 必须分页(项目中列表类需求、订单列表、商品列表、学生列表...)*/if (pageBean != null && pageBean.isPagination()) {// 必须分页(列表需求)String countSQL = getCountSQL(sql);pst = con.prepareStatement(countSQL);rs = pst.executeQuery();if (rs.next()) {pageBean.setTotal(String.valueOf(rs.getObject(1)));}// 挪动到下面,是因为最后才处理返回的结果集// -- sql=SELECT * FROM t_mvc_book WHERE bname like '%圣墟%'// -- pageSql=sql limit (page-1)*rows,rows 对应某一页的数据// -- countSql=select count(1) from (sql) t 符合条件的总记录数String pageSQL = getPageSQL(sql, pageBean);// 符合条件的某一页数据pst = con.prepareStatement(pageSQL);rs = pst.executeQuery();} else {// 不分页(select需求)pst = con.prepareStatement(sql);// 符合条件的所有数据rs = pst.executeQuery();}// 获取源数据ResultSetMetaData md = rs.getMetaData();int count = md.getColumnCount();Map<String, Object> map = null;while (rs.next()) {map = new HashMap<>();for (int i = 1; i <= count; i++) {
// map.put(md.getColumnName(i), rs.getObject(i));map.put(md.getColumnLabel(i), rs.getObject(i));}list.add(map);}return list;}
控制器类---UserAction
package com.ctb.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.ctb.dao.UserDao;
import com.ctb.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 biao** 2023年7月10日*/
public class UserAction extends ActionSupport implements ModelDriver<User> {private User user = new User();private UserDao ud = new UserDao();//登录public void login(HttpServletRequest req, HttpServletResponse resp) {try {User login = ud.login(user);ResponseUtil.writeJson(resp, login);} catch (Exception e) {e.printStackTrace();}}//注册public void register(HttpServletRequest req, HttpServletResponse resp) {try {int register = ud.register(user);if (register > 0) {ResponseUtil.writeJson(resp, "OK");} else {ResponseUtil.writeJson(resp, "NO");}} 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 = ud.listUserRole(user, pageBean);//查询方法
// Map<String, Object> map=new HashMap<String,Object>();
// map.put("code", 0);
// map.put("msg", "查询成功");
// map.put("count", pageBean.getTotal());
// map.put("data", userRole);
// ResponseUtil.writeJson(resp, map);ResponseUtil.writeJson(resp, R.ok(0, "查询成功", pageBean.getTotal(), userRole));} catch (Exception e) {e.printStackTrace();}}//新增public void add(HttpServletRequest req, HttpServletResponse resp) {try {int add = ud.add(user);if (add>0) {ResponseUtil.writeJson(resp, R.ok(0, "新增成功"));}else {ResponseUtil.writeJson(resp, R.error(0, "新增失败"));}} catch (Exception e) {e.printStackTrace();}}//编辑public void edit(HttpServletRequest req, HttpServletResponse resp) {try {int edit = ud.edit(user);if (edit>0) {ResponseUtil.writeJson(resp, R.ok(0, "编辑成功"));}else {ResponseUtil.writeJson(resp, R.ok(0, "编辑失败"));}} catch (Exception e) {e.printStackTrace();}}//删除public void del(HttpServletRequest req, HttpServletResponse resp) {try {int del = ud.del(user);if (del>0) {ResponseUtil.writeJson(resp, R.ok(0, "删除成功"));}else {ResponseUtil.writeJson(resp, R.ok(0, "删除失败"));}} catch (Exception e) {e.printStackTrace();}}@Overridepublic User getModel() {return user;}}
注:在用户管理查询中,我们是借助了R工具类
上图所示表格显示数据,是因为前端响应了数据。如果要用Layui框架就必须遵循它的回显数据的原则
R工具类,它继承自 HashMap,可用于构建包含响应数据的格式化结果。
主要方法如下:
1. data 方法 :用于向对象接受一个键和对应的值,并将其存储在R对象中。
2. R对象 受一个状态码`code`和 消息`msg` 作为参数,并通过`data`方法将相关数据存储进去。
3. error 方法:创建一个错误的`R`对象,接受一个状态码`code`和消息`msg`作为参数,并通过`data`方法将相关数据存储进去。4.三个重载的`ok`方法,用于创建包含更多数据R对象。该类主要用于简化构建统一的响应结果,方便在项目中使用。
三、前端JS编写
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(){//alert(123)queryall();});$("#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', '400px'], //宽高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();//调用查询方法刷新数据queryall();}else{layer.msg(rs.msg,function(){});}},'json');},btn2: function(index, layero){layer.closeAll();}});}//表格重载
function queryall(){table.reload('test', {where: { //设定异步数据接口的额外参数,任意设name: $("#name").val()},request: {pageName: 'page' //页码的参数名称,默认:page,limitName: 'rows' //每页数据量的参数名,默认:limit}
}); //只重载数据}
//表格数据初始化查询
function initTable(){table.render({elem: '#test',url:'user.action?methodName=userRole',title: '用户数据表',cols: [[{type: 'checkbox', fixed: 'left'},{field:'id', title:'ID', width:100, fixed: 'left', unresize: true, sort: true},{field:'name', title:'用户名', width:140, edit: 'text'},{field:'loginName', title:'账户名', width:150, edit: 'text', templet: function(res){return '<em>'+ res.loginName +'</em>'}},{field:'pwd', title:'密码', width:110, edit: 'text', sort: true},{field:'rname', title:'角色名', width:130},{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}]],page: true});//监听行工具事件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){//调用查询方法刷新数据queryall();}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');
}
在getData发方法中,通过form.val方法来获取表单的值,并返回该值
四、效果展示
1.查询演示
2.新增演示
3.修改演示
4.删除演示
layui数据表格的增删改查到这就结束啦 !!关注博主不迷路😁😁