录目
一、前期准备
前言:
上一次我们分享了layui的动态添加选项卡,这次要分享的内容是基于上一次的动态选项卡,在选项卡中使用layui完成用户管理功能。
目的效果展示:
数据库准备:
LayUi官网找到对应的代码源
以及我们目的效果图还需要搜索框的组件:
![](https://i-blog.csdnimg.cn/blog_migrate/c0c384ac477a45abe448861658e4e187.png)
我们将官网的前端代码以及js代码copy至我们的jsp页面中即可开始进一步编写后端代码,再我们要根据目的效果图进行修改
二、后端代码
UserDao:
package com.zking.dao;
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.PageBean;
import com.zking.util.StringUtils;
public class UserDao extends BaseDao<User>{
public User login(User user) throws Exception {
String sql = "select * from t_oa_user where loginName = '"+user.getLoginName()+"' and pwd = '"+user.getPwd()+"'";
List<User> users = super.executeQuery(sql, User.class,null);
return users == null || users.size() == 0 ? null : users.get(0);
}
// 查询用户信息以及对应角色,角色通过case when得出
public List<Map<String,Object>> list(User user,PageBean pageBean) throws Exception{
String sql = "SELECT * \r\n" +
",( CASE 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 ) roleName \r\n" +
"FROM \r\n" +
"t_oa_user 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 where name=?,loginName=?,pwd=? where id=?";
return super.executeUpdate(sql, user, new String[] {"name","loginName","pwd","id"});
}
}
在这里建议大家可以使用Junit进行测试在这丽小编就不展示了!
UserACtion:
package com.zking.web;
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 String login(HttpServletRequest req, HttpServletResponse resp) {
try {
User u = userDao.login(user);
if(u != null) {
ResponseUtil.writeJson(resp, R.ok(200, "成功"));
}else {
ResponseUtil.writeJson(resp, R.error(0, "账户或密码错误"));
}
} catch (Exception e) {
e.printStackTrace();
try {
ResponseUtil.writeJson(resp, R.error(0, "账户或密码错误"));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return null;
}
// 用户查询
public String list(HttpServletRequest req, HttpServletResponse resp) {
try {
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<Map<String, Object>> list = userDao.list(user, pageBean);
// 遵循layui中的格式
ResponseUtil.writeJson(resp, R.ok(0, "用户数据查询成功",pageBean.getTotal(),user));
} catch (Exception e) {
e.printStackTrace();
try {
ResponseUtil.writeJson(resp, R.error(0, "用户数据查询失败"));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return null;
}
public String add(HttpServletRequest req, HttpServletResponse resp) {
try {
int rs = userDao.add(user);
if(rs>0) {
ResponseUtil.writeJson(resp, R.ok(0, "用户数据新增成功"));
}else {
ResponseUtil.writeJson(resp, R.error(0, "用户数据新增失败"));
}
} catch (Exception e) {
e.printStackTrace();
try {
ResponseUtil.writeJson(resp, R.error(0, "用户数据新增失败"));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return null;
}
public String del(HttpServletRequest req, HttpServletResponse resp) {
try {
int rs = userDao.del(user);
if(rs>0) {
ResponseUtil.writeJson(resp, R.ok(0, "用户数据删除成功"));
}else {
ResponseUtil.writeJson(resp, R.error(0, "用户数据删除失败"));
}
} catch (Exception e) {
e.printStackTrace();
try {
ResponseUtil.writeJson(resp, R.error(0, "用户数据删除失败"));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return null;
}
public String edit(HttpServletRequest req, HttpServletResponse resp) {
try {
int rs = userDao.add(user);
if(rs>0) {
ResponseUtil.writeJson(resp, R.ok(0, "用户数据修改成功"));
}else {
ResponseUtil.writeJson(resp, R.error(0, "用户数据修改失败"));
}
} catch (Exception e) {
e.printStackTrace();
try {
ResponseUtil.writeJson(resp, R.error(0, "用户数据修改失败"));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return null;
}
@Override
public User getModel() {
return user;
}
}
配置文件在之前已经配置完成了,有第一次点进小编博客的可以参考前面的第三篇文章完成XML文件配置
三、前端代码
前端代码我们首先分析不仅仅是只有一个用户管理的目的界面,我们点击新增和修改的时候还需要弹出类似于模态框的新界面所以一共是两个界面
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">
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/system/userManage.js"></script>
<title>用户管理</title>
</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>
<!-- 对话框(新增和编辑共用一个页面) -->
<script type="text/html" id="toolbar">
<button class="layui-btn layui-btn-sm" lay-event="edit">编辑</button>
<button class="layui-btn layui-btn-sm" lay-event="del">删除</button>
<button class="layui-btn layui-btn-sm" lay-event="reset">重置密码</button>
</script>
</body>
</html>
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="${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>
对应的JS逻辑代码进行封装:
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', //指定原始表格元素选择器(推荐id选择器)
// url: 'user.action?methodName=list', //请求地址
height: 340, //自定义高度
loading: false, //是否显示加载条(默认 true)
cols: [[ //设置表头
{field: 'id', title: '用户编号', width: 120},
{field: 'name', title: '用户名', width: 120},
{field: 'loginName', title: '登录账号', width: 140},
{field: '', title: '操作', width: 220,toolbar:'#toolbar'},
]]
});
//在页面中的<table>中必须配置lay-filter="tb_goods"属性才能触发属性!!!
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($("#ctx").val()+'/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或者POST
loading: true, //是否显示加载条(默认 true)
page: true, //是否分页
where: { //设定异步数据接口的额外参数,任意设
'methodName':'list',
'name':$('#name').val()
},
request: { //自定义分页请求参数名
pageName: 'page', //页码的参数名称,默认:page
limitName: '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){
//jquery.find
//调用子页面中提供的getData方法,快速获取子页面的form表单数据
let data= $(layero).find("iframe")[0].contentWindow.getData();
console.log(data);
//判断title标题
let methodName="add";
if(title=="编辑")
methodName="edit";
$.post($("#ctx").val()+'/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
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:表格行对象
//table的数据在父页面userManager.js
//点击编辑按钮的时候,当前
form.val('user',$.extend({}, parent.row||{}));
$('#name').attr('readonly','readonly');
}
}
function getData(){
//<form class="layui-form layui-form-pane" lay-filter="user">
//取 user from中的值
return form.val('user');
}