为什么要用增删改查:
Layui是一个轻量级的前端UI库,被广泛应用于Web开发中。在开发过程中,经常需要对数据进行增删改查操作,这是因为数据是应用程序的核心内容,而增删改查是对数据进行基本的操作。
以下是几个原因解释为什么在Layui中使用增删改查操作:
- 数据管理和交互:对于大部分Web应用来说,用户需要与数据进行交互,包括增加新数据、删除不需要的数据、修改已有的数据以及查询获取所需的数据。增删改查操作是直接操作数据的方式,能够满足用户的需求。
- 数据展示与操作:Web应用通常需要以表格、列表等形式展示数据,而增删改查操作则是管理和操作这些数据的重要手段。通过增删改查操作,用户可以方便地管理和编辑数据,从而提升用户体验和操作效率。
- 安全性和数据完整性:通过对数据的增删改查操作,可以增强数据的安全性和完整性。例如,可以限制用户对数据的访问和操作权限,避免未经授权的人员对数据进行操作。
- 数据持久化:在Web开发中,数据通常需要永久保存并持久化到数据库,以便长期使用和管理。增删改查操作是对数据库中数据进行操作的方式,通过这些操作可以实现数据的持久化和管理。
- 总之,使用增删改查操作可以方便地管理、操作和展示数据,从而提供良好的用户体验和数据管理能力。Layui作为一个前端UI库,提供了方便易用的UI组件和交互方式,使得开发人员可以更快地实现增删改查功能。
1.后台增删改查方法:
查询语句:
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
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> { 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); } public User login(User user) throws Exception { String sql="select * from t_oa_user where loginName='"+user.getLoginName()+"' and pwd ='"+user.getPwd()+"' "; List<User> l = super.executeQuery(sql, User.class, null); if(l!=null && l.size()==1) { return l.get(0); } return user; } /** * 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 \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) value(?,?,?)"; return super.executeUpdate(sql, user, new String[] {"name","loginName","pwd"}); } public int del(User user) throws Exception { String sql="delete from t_oa_uesr where id=?"; return super.executeUpdate(sql, user, new String[] {"id"}); } public int edit(User user) throws Exception { String sql="update t_oa_uesr set name=?,loginName=?,pwd=? where id=?"; return super.executeUpdate(sql, user, new String[] {"name","loginName","pwd","id"}); } // public static void main(String[] args) throws Exception { // User user = new User("kk","123","123123"); // user.setName("朱"); // int add = new UserDao().add(user); // System.out.println(add); // } }
JUnit:
package com.zking.dao; import static org.junit.Assert.*; import java.util.List; import java.util.Map; import org.junit.Test; import com.zking.entity.User; public class UserDaoTest { private UserDao userDao =new UserDao(); @Test public void testUserRole() throws Exception { User user = new User(); user.setName("朱"); List<Map<String,Object>> userRole = userDao.userRole(user, null); for (Map<String,Object> u : userRole) { System.out.println(u); } } @Test public void testAdd() throws Exception { User user =new User(88, "朱俊良", "zjl", "12345", 4); userDao.add(user); } @Test public void testDel() throws Exception { User user =new User(88, "朱俊良", "zjl", "12345", 4); userDao.del(user); } @Test public void testEdit() throws Exception { User user =new User(16, "小飞机来了", "zjl", "1234567", 4); userDao.edit(user); } }
输出结果:
2.R工具类的使用:
后台查询:以前的写法: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.ResponseUtil; public class UserAction extends ActionSupport implements ModelDriver<User> { private User user=new User(); private UserDao userDao=new UserDao(); public void login(HttpServletRequest req, HttpServletResponse resp) { try { User u = userDao.login(user); ResponseUtil.writeJson(resp, u); } 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 = userDao.userRole(user, pageBean); Map<String, Object> map=new HashMap<String, Object>(); map.put("code", 0); map.put("msg", "查询成功"); map.put("count", pageBean.getTotal()); map.put("date", userRole); ResponseUtil.writeJson(resp, map); } catch (Exception e) { e.printStackTrace(); } } @Override public User getModel() { return user; } }
输出结果:
后台查询:现在的方法:工具类(代码较少,比较容易动懂):
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; } }
输出结果:
增删改查方法:
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(); public void login(HttpServletRequest req, HttpServletResponse resp) { try { User u = userDao.login(user); ResponseUtil.writeJson(resp, u); } 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 = userDao.userRole(user, pageBean); // Map<String, Object> map=new HashMap<String, Object>(); // map.put("code", 0); // map.put("msg", "查询成功"); // map.put("count", pageBean.getTotal()); // map.put("date", userRole); ResponseUtil.writeJson(resp, R.ok(0, "查询成功", pageBean.getTotal(), userRole)); } catch (Exception e) { e.printStackTrace(); } } public void add(HttpServletRequest req, HttpServletResponse resp) { try { int add = userDao.add(user ); ResponseUtil.writeJson(resp, R.ok(0, "新增成功")); } catch (Exception e) { e.printStackTrace(); } } public void del(HttpServletRequest req, HttpServletResponse resp) { try { int del = userDao.del(user ); ResponseUtil.writeJson(resp, R.ok(0, "删除成功")); } catch (Exception e) { e.printStackTrace(); } } public void edit(HttpServletRequest req, HttpServletResponse resp) { try { int edit = userDao.edit(user ); ResponseUtil.writeJson(resp, R.ok(0, "修改成功")); } catch (Exception e) { e.printStackTrace(); } } @Override public User getModel() { return user; } }
3.前端代码的实现:
编写UserManage界面:
<%@ 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>用户管理</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>
实现所有方法:
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; 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(); } }); } //1.初始化数据表格 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>中必须配置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('/user.action',{ 'methodName':'del', 'id':row.id },function(rs){ if(rs.success){ //调用查询方法刷新数据 query(); }else{ layer.msg(rs.msg,function(){}); } },'json'); layer.close(index); }); }else{ } }) } //查询 function query() { table.reload('test',{ where :{ name:$("name").val() } ,request:{ pageName:'page' ,limitName:'rows' } }); }
增加:
删除:
修改:
查询: