目录
一、前言
1.1 前言
1.2 前端代码(数据表格组件)
1.3 封装JS
二、LayUI增删改查的后台代码
2.1 编写Dao方法
2.1 增加
2.2 删除
2.3 修改
三、LayUI增删改查的前端代码
3.1 增加
一、前言
1.1 前言
上一篇文章我们一起做了LayUI的动态添加选项卡,这一篇文章我们继续来进行对LayUI的学习,开始编写一下LayUI的增删改查吧!
1.2 前端代码(数据表格组件)
这里就先把从官网上演变过来的一些前端代码粘贴过来: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;" lay-filter="tb_goods"></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>
1.3 封装JS
接着我们把我们需要的js全部封装好:userManage.js
let layer,$,table;
layui.use(['jquery', 'layer', 'table'], function(){layer = layui.layer,$ = layui.jquery,table = layui.table;//初始化数据表格initTable();//绑定查询按钮的点击事件$('#btn_search').click(function(){query();});
});//在页面中的<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{}
});//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'},]]});}//2.点击查询
function query(){table.reload('tb', {url: $("#ctx").val()+'/user.action', //请求地址method: 'POST', //请求方式,GET或者POSTloading: true, //是否显示加载条(默认 true)page: true, //是否分页where: { //设定异步数据接口的额外参数,任意设'methodName':'listUserRole','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表单数据//jQuery.findlet 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();}});
}
我们再放上引入的公共页面:header.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!-- 引入 layui.css -->
<link rel="stylesheet" href="${pageContext.request.contextPath }/static/js/layui/css/layui.css"><!-- 引入 layui.js -->
<script src="${pageContext.request.contextPath }/static/js/layui/layui.js"></script><!-- 指定整个项目的根路径 -->
<base href="${pageContext.request.contextPath }/" /><!-- 隐藏域传值 -->
<input id="ctx" value="${pageContext.request.contextPath }" type="hidden"/>
前端建立好了后,我们看看运行效果:
二、LayUI增删改查的后台代码
2.1 编写Dao方法
我们首先还是要写一个查询的方法:UserDao--->List
/*** 查询用户信息对应的角色,角色是通过case when得来的* @param user* @param pageBean* @return* @throws Exception*/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 \r\n" + ") 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);}
运行测试:
2.1 增加
我们继续编写增加的方法:Add
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"});}
2.2 删除
public int del(User user) throws Exception {String sql = "delete from t_oa_user where id = ?";return super.executeUpdate(sql, user, new String[] {"id"});}
2.3 修改
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"});}
当我们写好了增删改查的Dao方法后,就可以开始编写UserAction啦~
package com.leaf.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.leaf.dao.UserDao;
import com.leaf.entity.User;
import com.leaf.mvc.ActionSupport;
import com.leaf.mvc.ModelDriven;
import com.leaf.util.PageBean;
import com.leaf.util.R;
import com.leaf.util.ResponseUtil;public class UserAction extends ActionSupport implements ModelDriven<User> {private User user = new User();private UserDao ud = new UserDao();//写一个方法处理前台的请求public String login(HttpServletRequest req, HttpServletResponse resp) {Map<String, Object> map = new HashMap<String,Object>();try {//调用Dao方法User u = ud.login(user);if(u != null) {//登录成功//ResponseUtil.writeJson(resp, new R().data("code",200).data("msg", "成功"));ResponseUtil.writeJson(resp, R.ok(200, "登录成功"));}else {//登录失败//ResponseUtil.writeJson(resp, new R().data("code",0).data("msg", "账号密码错误"));ResponseUtil.writeJson(resp, R.ok(0, "用户名密码错误"));}} catch (Exception e) {e.printStackTrace();try {ResponseUtil.writeJson(resp, R.ok(0, "登录失败"));} catch (Exception e1) {e1.printStackTrace();}}return null;}//查询所有用户的方法public String list(HttpServletRequest req, HttpServletResponse resp) {try {PageBean pageBean = new PageBean();//初始化pageBean.setRequest(req);List<Map<String, Object>> list = ud.list(user, pageBean);ResponseUtil.writeJson(resp, R.ok(0, "查询成功" ,pageBean.getTotal() ,user));} catch (Exception e) {e.printStackTrace();try {ResponseUtil.writeJson(resp, R.ok(0, "查询失败"));} catch (Exception e1) {e1.printStackTrace();}}return null;}//增加的方法public String add(HttpServletRequest req, HttpServletResponse resp) {try {//rs是SQL语句执行的影响行数int rs = ud.add(user);//判断if(rs > 0) {ResponseUtil.writeJson(resp, R.ok(200, "新增成功"));}else {ResponseUtil.writeJson(resp, R.ok(0, "新增失败"));}} catch (Exception e) {e.printStackTrace();try {ResponseUtil.writeJson(resp, R.ok(0, "新增失败"));} catch (Exception e1) {e1.printStackTrace();}}return null;}//删除的方法public String del(HttpServletRequest req, HttpServletResponse resp) {try {//rs是SQL语句执行的影响行数int rs = ud.del(user);//判断if(rs > 0) {ResponseUtil.writeJson(resp, R.ok(200, "删除成功"));}else {ResponseUtil.writeJson(resp, R.ok(0, "删除失败"));}} catch (Exception e) {e.printStackTrace();try {ResponseUtil.writeJson(resp, R.ok(0, "删除失败"));} catch (Exception e1) {e1.printStackTrace();}}return null;}//修改的方法public String edit(HttpServletRequest req, HttpServletResponse resp) {try {//rs是SQL语句执行的影响行数int rs = ud.edit(user);//判断if(rs > 0) {ResponseUtil.writeJson(resp, R.ok(200, "修改成功"));}else {ResponseUtil.writeJson(resp, R.ok(0, "修改失败"));}} catch (Exception e) {e.printStackTrace();try {ResponseUtil.writeJson(resp, R.ok(0, "修改失败"));} catch (Exception e1) {e1.printStackTrace();}}return null;}@Overridepublic User getModel() {return user;}}
三、LayUI增删改查的前端代码
3.1 增加
我们需要建立一个增加的页面:userEdit
这个页面和编辑共用~
<%@ 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(){//取user from中的值return form.val('user');
}
OK,今天的学习笔记分享就到这里啦,我们呢下次再见!!!