前言
在前三篇layui博客的基础上继续完善,这篇博客增加了数据表格来实现增删改查
这里要注意layui需要使用2.6以上的版本文章来源:https://www.toymoban.com/news/detail-562362.html
dao方法的编写
package com.zking.dao;
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> {
/**
* 查询结果携带角色名称
* @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 \r\n" +
" WHEN u.rid='1' THEN\r\n" +
" '管理员'\r\n" +
" WHEN u.rid='2' THEN\r\n" +
" '发起者'\r\n" +
" WHEN u.rid='3' THEN\r\n" +
" '审批者'\r\n" +
" WHEN u.rid='4' THEN\r\n" +
" '参与者'\r\n" +
" WHEN u.rid='5' THEN\r\n" +
" '会议室管理员' \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 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 name=?,loginName=?,pwd=? where id = ?";
return super.executeUpdate(sql, user, new String[] {"name","loginName","pwd","id"});
}
}
servlet的编写
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 ud = new UserDao();
public void userRole(HttpServletRequest req, HttpServletResponse resp) {
try {
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<Map<String, Object>> userRole = ud.userRole(user, pageBean);
ResponseUtil.writeJson(resp, R.ok(0, "查询成功", pageBean.getTotal(), userRole));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void add(HttpServletRequest req, HttpServletResponse resp) {
try {
int add = ud.add(user);
ResponseUtil.writeJson(resp, R.ok(0, "新增成功"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void del(HttpServletRequest req, HttpServletResponse resp) {
try {
int add = ud.del(user);
ResponseUtil.writeJson(resp, R.ok(0, "删除成功"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void edit(HttpServletRequest req, HttpServletResponse resp) {
try {
int add = ud.edit(user);
ResponseUtil.writeJson(resp, R.ok(0, "修改成功"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public User getModel() {
// TODO Auto-generated method stub
return user;
}
}
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;
}
}
主界面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>Insert title here</title>
<script type="text/javascript" src="static/js/main.js"></script>
<style type="text/css">
.layui-tab-content,.layui-tab,.layui-from,.layui-table-box,.layui-body,.layui-tab-item,.layui-tab-item layui-show,.layui-table-body layui-table-main{
height:100%;
}
</style>
</head>
<body>
<div class="layui-layout layui-layout-admin">
<div class="layui-header">
<div class="layui-logo layui-hide-xs layui-bg-black">layout demo</div>
<!-- 头部区域(可配合layui 已有的水平导航) -->
<ul class="layui-nav layui-layout-left">
<!-- 移动端显示 -->
<li class="layui-nav-item layui-show-xs-inline-block layui-hide-sm" lay-header-event="menuLeft">
<i class="layui-icon layui-icon-spread-left"></i>
</li>
<!-- Top导航栏 -->
<li class="layui-nav-item layui-hide-xs"><a href="">nav 1</a></li>
<li class="layui-nav-item layui-hide-xs"><a href="">nav 2</a></li>
<li class="layui-nav-item layui-hide-xs"><a href="">nav 3</a></li>
<li class="layui-nav-item">
<a href="javascript:;">nav groups</a>
<dl class="layui-nav-child">
<dd><a href="">menu 11</a></dd>
<dd><a href="">menu 22</a></dd>
<dd><a href="">menu 33</a></dd>
</dl>
</li>
</ul>
<!-- 个人头像及账号操作 -->
<ul class="layui-nav layui-layout-right">
<li class="layui-nav-item layui-hide layui-show-md-inline-block">
<a href="javascript:;">
<img src="//tva1.sinaimg.cn/crop.0.0.118.118.180/5db11ff4gw1e77d3nqrv8j203b03cweg.jpg" class="layui-nav-img">
tester
</a>
<dl class="layui-nav-child">
<dd><a href="">Your Profile</a></dd>
<dd><a href="">Settings</a></dd>
<dd><a href="login.jsp">Sign out</a></dd>
</dl>
</li>
<li class="layui-nav-item" lay-header-event="menuRight" lay-unselect>
<a href="javascript:;">
<i class="layui-icon layui-icon-more-vertical"></i>
</a>
</li>
</ul>
</div>
<div class="layui-side layui-bg-black">
<div class="layui-side-scroll">
<!-- 左侧导航区域(可配合layui已有的垂直导航) -->
<ul id="menu" class="layui-nav layui-nav-tree" lay-filter="menu">
<li class="layui-nav-item layui-nav-itemed">
<a class="" href="javascript:;">menu group 1</a>
<dl class="layui-nav-child">
<dd><a href="javascript:;">menu 1</a></dd>
<dd><a href="javascript:;">menu 2</a></dd>
<dd><a href="javascript:;">menu 3</a></dd>
<dd><a href="">the links</a></dd>
</dl>
</li>
<li class="layui-nav-item">
<a href="javascript:;">menu group 2</a>
<dl class="layui-nav-child">
<dd><a href="javascript:;">list 1</a></dd>
<dd><a href="javascript:;">list 2</a></dd>
<dd><a href="">超链接</a></dd>
</dl>
</li>
<li class="layui-nav-item"><a href="javascript:;">click menu item</a></li>
<li class="layui-nav-item"><a href="">the links</a></li>
</ul>
</div>
</div>
<div class="layui-body">
<!-- 内容主体区域 -->
<div class="layui-tab" lay-filter="demo" lay-allowclose="true" style="height:100%;">
<ul class="layui-tab-title">
<li class="layui-this" lay-id="11">网站设置</li>
</ul>
<div class="layui-tab-content">
<div class="layui-tab-item layui-show">内容1</div>
</div>
</div>
</div>
<div class="layui-footer">
<!-- 底部固定区域 -->
底部固定区域
</div>
</div>
<script>
//JS
</script>
</body>
</html>
js代码
var element,layer,util,$;
layui.use(['element', 'layer', 'util'], function(){
element = layui.element
,layer = layui.layer
,util = layui.util
,$ = layui.$;
$.ajax({
url:'permission.action?methodName=menus',
dataType:'json',
success:function(data){
console.log(data)
var htmlStr = '';
$.each(data,function(i,n){
htmlStr +='<li class="layui-nav-item layui-nav-itemed">';
htmlStr +='<a class="" href="javascript:;">'+n.text+'</a>';
if(n.hasChildren){
var children=n.children;
htmlStr +='<dl class="layui-nav-child">';
$.each(children,function(index,node){
htmlStr +='<dd><a href="javascript:;" onclick="openTab(\''+node.text+'\',\''+node.attributes.self.url+'\',\''+node.id+'\')">'+node.text+'</a></dd>';
})
htmlStr +='</dl>';
}
htmlStr +='</li>';
})
$("#menu").html(htmlStr);
element.render('menu');
}
});
});
function openTab(title,content,id){
var $node = $('li[lay-id="'+id+'"]');
console.log($node)
if($node.length == 0){
//新增一个Tab项
element.tabAdd('demo', {
title: title //用于演示
,content: "<iframe frameborder='0' src='"+content+"' scrolling='auto' style='width:100%;height:100%;'></iframe>"
,id: id //实际使用一般是规定好的id,这里以时间戳模拟下
})
}
element.tabChange('demo', id); //切换到:用户管理
}
数据表格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/userManage.js"></script>
<title>Insert title here</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 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>
</body>
</html>
js代码
var table,$,layer;
var row;
layui.use(['table','jquery'], function(){
table = layui.table
,layer=layui.layer
,$=layui.jquery;
initTable();
$("#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();
}
});
}
function query(){
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'
,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('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('编辑');
}
});
}
编辑界面
<%@ 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代码
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');
}
运行效果如下:
文章来源地址https://www.toymoban.com/news/detail-562362.html
到了这里,关于layui增删改查的实现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!