1. CRUD是什么
CRUD 是一个表示数据处理操作的术语,它包含了增加 (Create)、读取 (Read)、更新 (Update) 和删除 (Delete) 这四个基本操作。这些操作是在应用程序中对数据进行持久化存储和管理时最常见的操作。
以下是对 CRUD 操作的详细说明:
1. 增加 (Create):表示向数据源中添加新的记录或对象。这可以是在数据库表中插入新行、在文件中追加新数据、发送 POST 请求来创建新资源等。用于创建操作的数据通常由用户通过界面输入或通过其他方式提供。
2. 读取 (Read):表示从数据源中获取(检索)现有的记录或对象。这可以是从数据库表中查询行、读取文件中的内容、从 API 获取数据等。用于读取操作的数据通常根据特定的条件进行查询和过滤。
3. 更新 (Update):表示对数据源中现有的记录或对象进行修改。这可以是在数据库表中更新行的值、编辑文件中的内容、发送 PUT 或 PATCH 请求来更新资源等。用于更新操作的数据通常根据特定的条件来定位要更新的对象,并提供要修改的新值。
4. 删除 (Delete):表示从数据源中删除现有的记录或对象。这可以是在数据库表中删除行、删除文件中的内容、发送 DELETE 请求来删除资源等。用于删除操作的数据通常根据特定的条件来定位要删除的对象。
2.CRUD
2.1 数据表
创建一个属性字段为如图所示中的 t_ou_User 表
2.2 数据库连接
2.2.1 文件config.properties
#mysql8 driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/mybatis_ssm?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT&useSSL=true user=root pwd=123456
其中mybatis_ssm是数据库名称,root是账号名称,123456是账号密码,根据自己的账号及数据库所修改才可以进行连接
2.2.2 连接类
package com.zking.util; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; /** * 提供了一组获得或关闭数据库对象的方法 * */ public class DBAccess { private static String driver; private static String url; private static String user; private static String password; static {// 静态块执行一次,加载 驱动一次 try { InputStream is = DBAccess.class .getResourceAsStream("config.properties"); Properties properties = new Properties(); properties.load(is); driver = properties.getProperty("driver"); url = properties.getProperty("url"); user = properties.getProperty("user"); password = properties.getProperty("pwd"); Class.forName(driver); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * 获得数据连接对象 * * @return */ public static Connection getConnection() { try { Connection conn = DriverManager.getConnection(url, user, password); return conn; } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } public static void close(ResultSet rs) { if (null != rs) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Statement stmt) { if (null != stmt) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Connection conn) { if (null != conn) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Connection conn, Statement stmt, ResultSet rs) { close(rs); close(stmt); close(conn); } public static boolean isOracle() { return "oracle.jdbc.driver.OracleDriver".equals(driver); } public static boolean isSQLServer() { return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver); } public static boolean isMysql() { return "com.mysql.cj.jdbc.Driver".equals(driver); } public static void main(String[] args) { Connection conn = DBAccess.getConnection(); System.out.println(conn); DBAccess.close(conn); System.out.println("isOracle:" + isOracle()); System.out.println("isSQLServer:" + isSQLServer()); System.out.println("isMysql:" + isMysql()); System.out.println("数据库连接(关闭)成功"); } }
2.3 实体(模型)
User 类/模型
package com.sy.entity; /** * @author 谌艳 * @com.CloudJun.entity * @User(说明):实体/模型类(User) */ public class User { private long id; private String name; private String loginName; private String pwd; private long rid; public User() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getloginName() { return loginName; } public void setloginName(String loginName) { this.loginName = loginName; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public long getRid() { return rid; } public void setRid(long rid) { this.rid = rid; } public User(long id, String name, String loginName, String pwd, long rid) { super(); this.id = id; this.name = name; this.loginName = loginName; this.pwd = pwd; this.rid = rid; } public User(String name, String loginName, String pwd) { super(); this.name = name; this.loginName = loginName; this.pwd = pwd; } public User(String name, String loginName, String pwd, long rid) { super(); this.name = name; this.loginName = loginName; this.pwd = pwd; this.rid = rid; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", loginName=" + loginName + ", pwd=" + pwd + ", rid=" + rid + "]"; } }
2.4 数据访问(Dao)
UserDao user数据的访问
package com.sy.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.List; import java.util.Map; import com.sy.entity.User; import com.zking.util.BaseDao; import com.zking.util.DBAccess; import com.zking.util.PageBean; import com.zking.util.StringUtils; public class UserDao extends BaseDao<User>{ /** * @param t * @return 进行删除用户后所影响的行数 * @throws Exception */ public int Add(User t) throws Exception { String sql = "insert into t_oa_user(name,loginName,pwd,rid) values(?,?,?,?)"; return super.executeUpdate(sql, t, new String [] {"name","loginName","pwd","rid"}); } /** * @param t * @return 进行删除用户后所影响的行数 * @throws Exception */ public int Del(User t) throws Exception { String sql = "delete from t_oa_user where id = ?"; return super.executeUpdate(sql, t, new String [] {"id"}); } /** * @param t * @return 进行修改用户后所影响的行数 * @throws Exception */ public int Edit(User t) throws Exception { String sql = "update t_oa_user set name = ?,loginName = ?, pwd = ? , rid = ? where id = ?"; return super.executeUpdate(sql, t, new String [] {"name","loginName","pwd","rid","id"}); } /** * 查询方法 * @param user * @param pageBean * @return * @throws Exception */ public List<Map<String, Object>> UserList(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 "; if(StringUtils.isNotBlank(user.getName())) { sql += " and name like '%"+user.getName()+"%' "; } return super.executeQuery(sql, pageBean); } //获取最大id public int getMaxId() throws Exception { //创建连接 Connection conn = DBAccess.getConnection(); int id = 0; String sql = "select MAX(id) from t_oa_user"; PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); if(rs.next()) { id = rs.getInt(1); } return id; } //测试 public static void main(String[] args) throws Exception { int maxId = new UserDao().getMaxId(); System.out.println(maxId); User user = new User("大司马", "dsm", "123456",3); //增加方法调用 int register = new UserDao().Add(user); System.out.println(register); } }
其中基础了BaseDao的工具类
BaseDao
package com.zking.util; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 所有Dao层的父类 BookDao UserDao OrderDao ... * * @author Administrator * * @param <T> */ public class BaseDao<T> { /** * 适合多表联查的数据返回 * @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; } /** * * @param sql * @param attrs * map中的key * @param paMap * jsp向后台传递的参数集合 * @return * @throws SQLException * @throws NoSuchFieldException * @throws SecurityException * @throws IllegalArgumentException * @throws IllegalAccessException */ public int executeUpdate(String sql, String[] attrs, Map<String, String[]> paMap) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Connection con = DBAccess.getConnection(); PreparedStatement pst = con.prepareStatement(sql); for (int i = 0; i < attrs.length; i++) { pst.setObject(i + 1, JsonUtils.getParamVal(paMap, attrs[i])); } return pst.executeUpdate(); } /** * 批处理 * @param sqlLst * @return */ public static int executeUpdateBatch(String[] sqlLst) { Connection conn = null; PreparedStatement stmt = null; try { conn = DBAccess.getConnection(); // 设置不自动提交 conn.setAutoCommit(false); for (String sql : sqlLst) { stmt = conn.prepareStatement(sql); stmt.executeUpdate(); } conn.commit(); } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); throw new RuntimeException(e1); } e.printStackTrace(); throw new RuntimeException(e); } finally { DBAccess.close(conn, stmt, null); } return sqlLst.length; } /** * 通用的增删改方法 * * @param book * @throws Exception */ public int executeUpdate(String sql, T t, String[] attrs) throws Exception { // String[] attrs = new String[] {"bid", "bname", "price"}; Connection con = DBAccess.getConnection(); PreparedStatement pst = con.prepareStatement(sql); // pst.setObject(1, book.getBid()); // pst.setObject(2, book.getBname()); // pst.setObject(3, book.getPrice()); /* * 思路: 1.从传进来的t中读取属性值 2.往预定义对象中设置了值 * * t->book f->bid */ for (int i = 0; i < attrs.length; i++) { Field f = t.getClass().getDeclaredField(attrs[i]); f.setAccessible(true); pst.setObject(i + 1, f.get(t)); } return pst.executeUpdate(); } /** * 通用分页查询 * * @param sql * @param clz * @return * @throws Exception */ public List<T> executeQuery(String sql, Class<T> clz, PageBean pageBean) throws Exception { List<T> list = new ArrayList<T>(); 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(); } while (rs.next()) { T t = clz.newInstance(); Field[] fields = clz.getDeclaredFields(); for (Field f : fields) { f.setAccessible(true); f.set(t, rs.getObject(f.getName())); } list.add(t); } return list; } /** * 将原生SQL转换成符合条件的总记录数countSQL * * @param sql * @return */ private String getCountSQL(String sql) { // -- countSql=select count(1) from (sql) t 符合条件的总记录数 return "select count(1) from (" + sql + ") t"; } /** * 将原生SQL转换成pageSQL * * @param sql * @param pageBean * @return */ private String getPageSQL(String sql, PageBean pageBean) { // (this.page - 1) * this.rows // pageSql=sql limit (page-1)*rows,rows return sql + " limit " + pageBean.getStartIndex() + "," + pageBean.getRows(); } }
BaseDao中也用到了JsonUtils工具类
package com.zking.util; import java.util.Arrays; import java.util.Map; /** * 专门用来处理json数据的工具包 * @author Administrator * */ public class JsonUtils { /** * 从paramMap拿到咱们所需要用到的查询维度,用于sql语句拼接 * @param paramMap 获取从jsp页面传递到后台的参数集合(req.getParamterMap) * @param key * @return */ public static String getParamVal(Map<String,String[]> paramMap, String key) { if(paramMap != null && paramMap.size()>0) { String[] vals = paramMap.get(key); if(vals != null && vals.length > 0) { String val = Arrays.toString(vals); return val.substring(1, val.length()-1); } return ""; } return ""; } }
2.5 控制器
UserAction是user控制器,用来处理请求,反馈数据到前端页面
UserAction代码
package com.sy.web; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sy.dao.UserDao; import com.sy.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 Add(HttpServletRequest req,HttpServletResponse reps) { try { int i = ud.Add(user); //判断方法执行后就结果,给出相应的处理 if(i>0) { //借用R工具类进行代码简化 ResponseUtil.writeJson(reps, R.ok(0, "新增成功")); }else { ResponseUtil.writeJson(reps, R.ok(0, "新增失败")); } } catch (Exception e) { e.printStackTrace(); } } public void Del(HttpServletRequest req,HttpServletResponse reps) { try { int i = ud.Del(user); //判断方法执行后就结果,给出相应的处理 if(i>0) { //借用R工具类进行代码简化 ResponseUtil.writeJson(reps, R.ok(0, "删除成功")); }else { ResponseUtil.writeJson(reps, R.ok(0, "输出失败")); } } catch (Exception e) { e.printStackTrace(); } } public void Edit(HttpServletRequest req,HttpServletResponse reps) { try { int i = ud.Edit(user); //判断方法执行后就结果,给出相应的处理 if(i>0) { //借用R工具类进行代码简化 ResponseUtil.writeJson(reps, R.ok(0, "修改成功")); }else { ResponseUtil.writeJson(reps, R.ok(0, "修改失败")); } } catch (Exception e) { e.printStackTrace(); } } public void UserList(HttpServletRequest req,HttpServletResponse reps) { PageBean pageBean = new PageBean(); pageBean.setRequest(req); try { List<Map<String, Object>> Userlist = ud.UserList(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", Userlist);*/ //借用R工具类进行代码简化 ResponseUtil.writeJson(reps, R.ok(0, "查询成功",pageBean.getTotal(),Userlist)); } catch (Exception e) { e.printStackTrace(); } } @Override public User getModel() { return user; } }
其中继承的 ActionSupport类(所有模型控制器的总控制器,相当于父类的意思)和实现ModelDriver
接口(模型驱动接口)该两个都是自定义框架里面已经编写好了的架包及功能。
还用到了两个工具类ResponseUtil和R类
ResponseUtil作用是将数组或者集合转化为键值对的字符串转入前端获取
R : 结合Layui中数据表格的结构进行数据加入,然后通过ResponseUtil转入前端获取
ResponseUtil代码如下
package com.zking.util; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import com.fasterxml.jackson.databind.ObjectMapper; public class ResponseUtil { public static void write(HttpServletResponse response,Object o)throws Exception{ response.setContentType("text/html;charset=utf-8"); PrintWriter out=response.getWriter(); out.println(o.toString()); out.flush(); out.close(); } public static void writeJson(HttpServletResponse response,Object o)throws Exception{ ObjectMapper om = new ObjectMapper(); // om.writeValueAsString(o)代表了json串 write(response, om.writeValueAsString(o)); } }
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; } }
3.前端代码
使用以下代码要导入及引入js,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 src="static/JS/index.js"></script> </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"> </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"> <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> </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"> <title>用户新增</title> <script type="text/javascript" src="static/js/userEdit.js"></script> </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>
其中两个页面到导入了资源页面 header.jsp
代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html > <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <!-- 引入 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> <link rel="stylesheet" rev="stylesheet" href="${pageContext.request.contextPath }/static/css/iconfont.css" type="text/css" media="all"> <link rel="stylesheet" rev="stylesheet" href="${pageContext.request.contextPath }/static/css/login.css" type="text/css" media="all"> <base href="${pageContext.request.contextPath }/" />
js
UserManage.jsp中引入的js(UserManage.js)
UserManage.js作用是拿到Layui中的数据表格优化,后进行数据访问,调用方法获取数据库中的数据到前端页面的表格中显示,之后进行增删改查的操作
UserManage.js代码
let layer,util,$,table; var row; layui.use(['table','jquery'], function(){ table = layui.table; $ = layui.jquery; layer = layui.layer; //表格数据的初始化 Tableinit(); //查询的点击事件 $("#btn_search").click(function(){ query() }); //新增的点击事件 $("#btn_add").click(function(){ row=null; edit("新增用户") }); }); //3.对话框 function edit(title){ layer.open({ //layer提供了5种层类型。可传入的值有:0(信息框,默认)1(页面层)2(iframe层)3(加载层)4(tips层) type: 2, title:title, area: ['660px', '380px'], //宽高 skin: 'layui-layer-rim', //样式类名 content:'jsp/UserSystem/userEdit.jsp', //书本编辑页面 btn:['保存','关闭'], yes: function(index, layero){ //这里的弹出层是嵌入了一个页面(userEdit.jsp),除按钮以为都不是本页面(UserManage.jsp)的代码 //调用子页面中(userEdit.jsp)提供的getData方法,快速获取子页面(userEdit.jsp)的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.alert('新增成功', {icon: 1}); //关闭对话框 layer.closeAll(); //调用查询方法刷新数据 query(); }else{ layer.msg(rs.msg,function(){}); } },'json'); }, close: function(index, layero){ layer.closeAll(); } }); } //点击查询,表格重载 function query(){ //只重载数据 table.reload('tb', { where: { //设定异步数据接口的额外参数,任意设 name: $("#name").val() } ,page: { curr: 1 //重新从第 1 页开始 } }); } /*table.reload('tb', { url: 'user.action?methodName=UserList'+$("#name").val(), //请求地址 method: 'POST', //请求方式,GET或者POST loading: true, //是否显示加载条(默认 true) page: true, //是否分页 where: { //设定异步数据接口的额外参数,任意设 'methodName':'listUserRole', 'name':$('#name').val() }, request: { //自定义分页请求参数名 pageName: 'page', //页码的参数名称,默认:page limitName: 'rows' //每页数据量的参数名,默认:limit } });*/ //表格数据初始化方法 function Tableinit(){ table.render({ elem: '#tb' ,url:'user.action?methodName=UserList' ,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:'name', title:'用户名称', width:120, edit: 'text'} ,{field:'loginName', title:'用户账号', width:150, edit: 'text', templet: function(res){ return '<em>'+ res.loginName +'</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('tool(test)', function(obj){ row = obj.data; console.log(row); if(obj.event === 'del'){ layer.confirm('真的删除该行数据么/(ㄒoㄒ)/~~', 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("编辑用户") } }); }
userEdit.jsp中引入的js(userEdit.js)
userEdit.js作用是这里的弹出层是嵌入了一个页面(userEdit.jsp),除按钮以为都不是本页面(UserManage.jsp)的代码
调用子页面中(userEdit.jsp)提供的getData方法,快速获取子页面(userEdit.jsp)的form表单数据
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'); }