zoukankan      html  css  js  c++  java
  • Layui连接mysql操作CRUD案例

    今天分享的是一个新前端框架Layui,用它来链接数据库实现一下crud的操作。

    一:layui简历

      layui,是一款采用自身模块规范编写的前端 UI 框架,遵循原生 HTML/CSS/JS 的书写与组织形式,门槛极低,拿来即用。其外在极简,却又不失饱满的内在,体积轻盈,组件丰盈,从核心代码到 API 的每一处细节都经过精心雕琢,非常适合界面的快速开发;它坚持采用经典模块化,也正是能让人避开工具的复杂配置,重新回归到原生态的 HTML/CSS/JavaScript本身。

      本身它的历史就不长,18年五月份发布,所以还是比较跟进时代技术,值得学习的。

      layui官网(https://www.layui.com/demo/

    二:使用layui框架实现权限登陆显示树形菜单

      2.1  首先引用一下layui框架所需的包

      

      2.2  创建二星权限显现树形菜单所需要的表和所需要操作的书本类型表

      用户表t_xm_user

       树形菜单展现所需的权限表 t_book_menu

       中间权限表t_usermenuid

      书本类型表t_book_category2

     准备下面代码中所需要的包工具包:

    https://pan.baidu.com/s/1XnwIoJQUDyw0cJads5Pddw

      在项目中配置与mysql数据库连接

      

       2.3  权限登陆

      userDao类

    package com.ht.dao;
    
    import java.sql.SQLException;
    import java.util.List;
    import java.util.Map;
    
    import com.ht.daoimpl.IUserDao;
    import com.ht.util.JsonBaseDao;
    import com.ht.util.JsonUtils;
    import com.ht.util.PageBean;
    import com.ht.util.StringUtils;
    
    public class UserDao extends JsonBaseDao implements IUserDao{
        /**
         * 登陆查询用户表
         * @param paMap
         * @param pageBean
         * @return
         * @throws SQLException 
         * @throws IllegalAccessException 
         * @throws InstantiationException 
         */
        public List<Map<String,Object>> list(Map<String,String[]> paMap,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
            String sql="select * from t_xm_user where true";
            String user_name=JsonUtils.getParamVal(paMap, "user_name");
            String user_pwd=JsonUtils.getParamVal(paMap, "user_pwd");
            if (StringUtils.isNotBlank(user_name)) {
                sql= sql +" and user_name ="+user_name;
            }
            if (StringUtils.isNotBlank(user_pwd)) {
                sql= sql +" and user_pwd ="+user_pwd;
            }
            return super.executeQuery(sql, pageBean);
        }
        /**
         * 通过中间表查询登陆用户所对应的权限
         * @param paMap
         * @param pageBean
         * @return
         * @throws InstantiationException
         * @throws IllegalAccessException
         * @throws SQLException
         */
        public List<Map<String,Object>> listMenu(String user_id,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
            String sql="select * from t_usermenuid where true";
            if (StringUtils.isNotBlank(user_id)) {
                sql= sql +" and user_id ="+user_id;
            }
            return super.executeQuery(sql, pageBean);
        }
    }

    web层

      userAction类

    package com.ht.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.fasterxml.jackson.databind.ObjectMapper;
    import com.ht.dao.UserDao;
    import com.zking.framework.ActionSupport;
    import com.ht.util.PageBean;
    import com.ht.util.ResponseUtil;
    import com.ht.util.StringUtils;
    
    public class UserAction extends ActionSupport {
        private UserDao uesrDao = new UserDao();
        public String login(HttpServletRequest req, HttpServletResponse rep) {
            try {
                List<Map<String, Object>> list = this.uesrDao.list(req.getParameterMap(), null);
                if (list != null && list.size() > 0) {
                    List<Map<String, Object>> listmenu = this.uesrDao.listMenu(req.getParameter("user_name"), null);
                    StringBuffer sb = new StringBuffer();
                    for (Map<String, Object> map : listmenu) {
                        sb.append("," + map.get("Menuid"));
                    }
                    req.getSession().setAttribute("menuhid", sb.substring(1));
                    return "index";
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return "login";
        }
        /**
         * datagrid所需数据后端程序员开发完毕
         * @param req
         * @param resp
         * @return
         */
        public String list(HttpServletRequest req,HttpServletResponse resp){
            try {
                PageBean pageBean=new PageBean();
                pageBean.setRequest(req);
                List<Map<String, Object>> list = this.uesrDao.list(req.getParameterMap(), pageBean);
                ObjectMapper om=new ObjectMapper();
                //数据格式转换
                Map<String, Object> map=new HashMap<>();
                map.put("total", pageBean.getTotal());
                map.put("rows", list);
                ResponseUtil.write(resp, om.writeValueAsString(map));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
            return null;
        }
        
    }

      login.jsp 显示登陆界面

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
        <link href="${pageContext.request.contextPath }/css/shop.css" type="text/css" rel="stylesheet"/>
        <link href="${pageContext.request.contextPath }/css/skin.css" rel="stylesheet" type="text/css"/>
        <link href="${pageContext.request.contextPath }/css/Sellerber.css" type="text/css" rel="stylesheet" />
        <link href="${pageContext.request.contextPath }/css/bkg_ui.css" type="text/css" rel="stylesheet" />
        <link href="${pageContext.request.contextPath }/css/font-awes0ome.min.css" rel="stylesheet" type="text/css" />
        <script src="${pageContext.request.contextPath }/static/js/jquery-1.9.1.min.js" type="text/javascript"></script>
        <script src="${pageContext.request.contextPath }/static/js/layer.js" type="text/javascript"></script>
        <script src="${pageContext.request.contextPath }/static/js/bootstrap.min.js" type="text/javascript"></script>
        <script src="${pageContext.request.contextPath }/static/js/Sellerber.js" type="text/javascript"></script>
        <script src="${pageContext.request.contextPath }/static/js/shopFrame.js" type="text/javascript"></script>
        <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery.cookie.js"></script>
        <script type="text/javascript" src="${pageContext.request.contextPath }/js/login.js"></script>
        <title>用户登录</title>
    </head>
    <body class="login-layout Reg_log_style" onload="mya()">
        <div class="logintop">
            <span>欢迎后台管理界面平台</span>
        </div>
        <div class="loginbody">
            <div class="login-container">
                <div class="center">
                    <img src="images/logo.png" />
                </div>
                <div class="space-6"></div>
                <div class="position-relative">
                    <div id="login-box" class="login-box widget-box no-border visible">
                        <div class="login-main">
                            <div class="clearfix">
                                <div class="login_icon">
                                    <img src="images/login_img.png" />
                                </div>
                                <form action="${pageContext.request.contextPath}/userAction.action?methodName=login"
                                    method="post"
                                    style=" 300px; float: right; margin-right: 50px;"
                                    onsubmit="return vlogin()">
                                    <h4 class="title_name">
                                        <img src="images/login_title.png" />
                                    </h4>
                                    <fieldset>
                                        <ul>
                                            <li class="frame_style form_error"><label
                                                class="user_icon"></label> <input name="user_name"
                                                type="text" placeholder="请输入用户名" id="username" /><span
                                                id="username" style="color: red;"></span></li>
                                            <li class="frame_style form_error"><label
                                                class="password_icon"></label> <input name="user_pwd"
                                                type="password" placeholder="请输入密码" id="userpwd" /><span
                                                id="userpwd" style="color: red;"></span></li>
                                            <li class="frame_style form_error"><label
                                                class="Codes_icon"></label><input type="text" id="yzm" placeholder="请输入正确验证码"/>
                                            <div class="Codes_region">
                                                    <span id="yz" style="color: red;">X X X X</span>
                                                </div></li>
                                        </ul>
                                        <div class="space"></div>
                                        <div class="clearfix">
                                            <input type="submit" class="login_btn" value="登陆" />
                                        </div>
                                        <div class="space-4"></div>
                                    </fieldset>
                                </form>
                            </div>
                    </div>
                    <!-- /login-box -->
                </div>
                <!-- /position-relative -->
            </div>
        </div>
        </div>
    </body>
    </html>

      配置xml

    <action path="/userAction" type="com.ht.web.UserAction">
            <forward name="login" path="/login.jsp" redirect="false" />
        </action>

        效果如下:

       2.4  树形菜单显示

      对树形菜单的格式进行描述  写一个TreeNode

    package com.ht.entity;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class TreeNode {
        private String id;
        private String name;
        private Map<String, Object> attributes = new HashMap<>();
        private List<TreeNode> children = new ArrayList<>();
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Map<String, Object> getAttributes() {
            return attributes;
        }
    
        public void setAttributes(Map<String, Object> attributes) {
            this.attributes = attributes;
        }
    
        public List<TreeNode> getChildren() {
            return children;
        }
    
        public void setChildren(List<TreeNode> children) {
            this.children = children;
        }
    
        public TreeNode(String id, String text, Map<String, Object> attributes, List<TreeNode> children) {
            super();
            this.id = id;
            this.name = name;
            this.attributes = attributes;
            this.children = children;
        }
    
        public TreeNode() {
            super();
        }
    
        @Override
        public String toString() {
            return "TreeNode [id=" + id + ", name=" + name + ", attributes=" + attributes + ", children=" + children + "]";
        }
    
    }

      dao层 MenuDao类 

      在dao类中使用了递归来转换josn格式,因为layui只能识别这种格式

    package com.ht.dao;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import com.ht.daoimpl.IMenuDao;
    import com.ht.entity.TreeNode;
    import com.ht.util.JsonBaseDao;
    import com.ht.util.JsonUtils;
    import com.ht.util.PageBean;
    import com.ht.util.StringUtils;
    /**
     * 树形权限管理类
     * @author Administrator
     *
     */
    public class MenuDao extends JsonBaseDao implements IMenuDao{
    
        /**
         * 
         * @param map   req.getParameterMap
         * @param pageBean  分页
         * @return
         * @throws Exception 
         */
        public List<TreeNode> list(Map<String, String[]> map,PageBean pageBean) throws Exception{
            List<Map<String, Object>> listMenu=this.listMenuSef(map, pageBean);
            List<TreeNode> treeNodeList=new ArrayList<>();
            menuList2TreeNodeList(listMenu, treeNodeList);
            return treeNodeList;
        }
        /**
         * 查询子节点
         * @param map
         * @param pageBean
         * @return
         * @throws Exception
         */
        public List<Map<String, Object>> listMenuSef(Map<String, String[]> map,PageBean pageBean)throws Exception{
            String sql=" select * from t_book_menu where true";
            String id=JsonUtils.getParamVal(map, "menuhid");
            if(StringUtils.isNotBlank(id)) {
                sql= sql + " and Menuid in ("+id+")";    
            }
            else {  
                sql= sql + " and Menuid =-1";
            }
            return super.executeQuery(sql, pageBean);
        }
        /**
         * 查询Menu表的数据
         * @param map
         * @param pageBean
         * @return
         */
        public List<Map<String, Object>> listMenu(Map<String, String[]> map,PageBean pageBean)throws Exception{
            String sql=" select * from t_book_menu where true";
            String id=JsonUtils.getParamVal(map, "id");
            if(StringUtils.isNotBlank(id)) {
                sql= sql + " and parentid ="+id;    
            }
            else {
                sql= sql + " and parentid = -1";
            }
            return super.executeQuery(sql, pageBean);
        }
        
        /**
         * {Menuid:1,....[]}
         * ->{id:1,....[]}
         * menu表的数据不符合easyui树形展示的数据格式
         * 需要转换成easyui所能识别的数据格式
         * @param map
         * @param reTreeNode
         * @throws Exception 
         */
        public void menu2TreeNode(Map<String, Object> map, TreeNode treeNode) throws Exception {
            treeNode.setId(map.get("Menuid").toString());
            treeNode.setName(map.get("Menuname").toString());
            treeNode.setAttributes(map);
            Map<String, String[]> jspMap=new HashMap<>();
            jspMap.put("id", new String[] {treeNode.getId()});
            this.listMenu(jspMap, null);
            List<Map<String, Object>> listMenu=this.listMenu(jspMap, null);
            List<TreeNode> treeNodeList=new ArrayList<>();
            menuList2TreeNodeList(listMenu, treeNodeList);
            treeNode.setChildren(treeNodeList);
        }
        /**
         * [{Menuid:1,....[]},{Menuid:2,....[]}]
         * ->[{id:1,....[]},{id:2,....[]}]
         * @param mapList
         * @param treeNodeList
         * @throws Exception
         */
        public void menuList2TreeNodeList(List<Map<String, Object>> mapList, List<TreeNode> treeNodeList)throws Exception {
            TreeNode treeNode =null;
            for (Map<String, Object> map : mapList) {
                treeNode =new TreeNode();
                menu2TreeNode(map, treeNode);
                treeNodeList.add(treeNode);
            }
        }
    }

     web层

    MenuAction类
    package com.ht.web;
    
    import java.io.PrintWriter;
    import java.sql.SQLException;
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.ht.biz.MenuBiz;
    import com.ht.bizipml.IMenuBiz;
    import com.ht.dao.MenuDao;
    import com.ht.entity.TreeNode;
    import com.zking.framework.ActionSupport;
    import com.ht.util.ResponseUtil;
    
    public class MenuAction extends ActionSupport {
        private IMenuBiz menuDao = new MenuBiz();
        public String treeMenu(HttpServletRequest req, HttpServletResponse response) throws Exception {
            @SuppressWarnings("unchecked")
            List<TreeNode> list = this.menuDao.list(req.getParameterMap(), null);
            ObjectMapper om = new ObjectMapper();
            String jsonStr = om.writeValueAsString(list);
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out=response.getWriter();
            out.println(jsonStr);
            out.flush();
            out.close();
            return null;
        }
    }

       index.jsp  显示树形菜单

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <html >
    <head>
        <meta charset="UTF-8">
        <title></title>
        <link rel="stylesheet" href="${pageContext.request.contextPath }/static/js/layui/css/layui.css" media="all">
        <script src="${pageContext.request.contextPath }/static/js/layui/layui.js"></script>
        <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery-3.3.1.js"></script>
        <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/layui/layui.all.js"></script>
        <link rel="stylesheet" href="${pageContext.request.contextPath }/static/js/layui/css/index.css"> 
        <script type="text/javascript" src="${pageContext.request.contextPath }/js/index.js"></script>
    </head>
    
    <body>
    <input type="hidden" id="menuhid" value="${menuhid}">
    <div class="layui-layout layui-layout-admin " id="app">
        <div class="layui-header">
            <div class="layui-logo">后台管理界面</div>
            <!-- 头部区域(可配合layui已有的水平导航) -->
            <ul class="layui-nav layui-layout-right">
                <li class="layui-nav-item"><a href="#" onclick="exit()">退出登录</a></li>
            </ul>
        </div>
        <!-- 左边tree页面 -->
        <div class="layui-side layui-bg-black">
            <div class="layui-side-scroll ">
                <div id="demo" ></div>
            </div>
        </div>
        <!-- 选项卡要显示的地方 -->
        <div class="layui-body">
            <div class="layui-tab" lay-filter="tabs" lay-allowClose="true">
                <ul class="layui-tab-title">
                </ul>
                <div class="layui-tab-content">
                </div>
            </div>
        </div>
        <div class="layui-footer" align="center" >
            <!-- 底部固定区域 -->
            © layui.com - 底部固定区域
        </div>
    </div>
    </body>
    </html>

    配置xml  

    <action path="/menuAction" type="com.ht.web.MenuAction">
            <forward name="index" path="/index.jsp" redirect="false" />
        </action>

    效果图:

      

     三:使用layui框架实现增,删,改,查

      dao层,从数据库中拿出数据并且对其进行增,删,改,查操作

    package com.ht.dao;
    
    import java.sql.SQLException;
    import java.util.List;
    import java.util.Map;
    
    import com.ht.daoimpl.IBooktypeDao;
    import com.ht.util.JsonBaseDao;
    import com.ht.util.JsonUtils;
    import com.ht.util.PageBean;
    import com.ht.util.StringUtils;
    /**
     * 书籍类别管理
     * @author Administrator
     *
     */
    public class BooktypeDao extends JsonBaseDao implements IBooktypeDao{
        /**
         * 编辑用户信息 查询书本类型表
         * @param paMap
         * @return
         * @throws Exception
         */
        public int edit(Map<String, String[]> paMap) throws Exception {
            String sql = "update t_book_category2 set book_category_name=? where book_category_id=?";
            return super.executeUpdate(sql, new String[] { "book_category_name","book_category_id" }, paMap);
        }
        /**
         * 新增 查询书本类型表
         * @param paMap
         * @return
         * @throws Exception
         */
        public int add(Map<String, String[]> paMap) throws Exception {
            String sql = "INSERT INTO t_book_category2(book_category_name) VALUES(?)";
            return super.executeUpdate(sql, new String[] { "book_category_name" }, paMap);
        }
        /**
         * 删除 查询书本类型表
         * @param paMap
         * @return
         * @throws Exception
         */
        public int remove(Map<String, String[]> paMap) throws Exception {
            String sql = "DELETE FROM t_book_category2 WHERE  book_category_id=?";
            return super.executeUpdate(sql, new String[] { "book_category_id" }, paMap);
        }
        /**
         * 查询的方法
         * @param paMap
         * @param pageBean
         * @return
         * @throws InstantiationException
         * @throws IllegalAccessException
         * @throws SQLException
         */
        public List<Map<String, Object>> select(Map<String, String[]> paMap, PageBean pageBean)
                throws InstantiationException, IllegalAccessException, SQLException {
            String sql = "select * from t_book_category2 where true";
            String book_category_name = JsonUtils.getParamVal(paMap, "book_category_name");
            if (StringUtils.isNotBlank(book_category_name)) {
                sql = sql + " and book_category_name  like '%" + book_category_name + "%'";
            }
            return super.executeQuery(sql, pageBean);
        }
    }

    web层

      BooktypeAction类

    package com.ht.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.fasterxml.jackson.databind.ObjectMapper;
    import com.ht.biz.BooktypeBiz;
    import com.ht.bizipml.IBooktypeBiz;
    import com.ht.dao.BooktypeDao;
    import com.zking.framework.ActionSupport;
    import com.ht.util.PageBean;
    import com.ht.util.ResponseUtil;
    
    public class BooktypeAction extends ActionSupport{
    
        private IBooktypeBiz booktypeDao=new BooktypeBiz();
        /**
         * 查询的请求方法
         * @param req
         * @param resp
         * @return
         */
        public String select(HttpServletRequest req,HttpServletResponse resp) {
            try {
                PageBean pageBean=new PageBean();
                pageBean.setRequest(req);
                List<Map<String, Object>> list = this.booktypeDao.select(req.getParameterMap(), pageBean);
                ObjectMapper om=new ObjectMapper();
                Map<String, Object> map=new HashMap<>();
                map.put("total", pageBean.getTotal());
                map.put("rows", list);
                ResponseUtil.write(resp, om.writeValueAsString(map));
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
            return "index";
            
        }
        /**
         * form组件提交所需数据后端程序员处理完毕
         * @param req
         * @param resp
         * @return
         */
        public String edit(HttpServletRequest req,HttpServletResponse resp){
            try {
                int edit = this.booktypeDao.edit(req.getParameterMap());
                ObjectMapper om=new ObjectMapper();
                ResponseUtil.write(resp, om.writeValueAsString(edit));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
            return null;
        }
        /**
         * 新增的请求方法
         * @param req
         * @param resp
         * @return
         */
        public String add(HttpServletRequest req,HttpServletResponse resp){
            try {
                int add = this.booktypeDao.add(req.getParameterMap());
                ObjectMapper om=new ObjectMapper();
                ResponseUtil.write(resp, om.writeValueAsString(add));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
            return null;
        }
        /**
         * 删除的请求方法
         * @param req
         * @param resp
         * @return
         */
        public String remove(HttpServletRequest req,HttpServletResponse resp) {
            try {
                int remove=this.booktypeDao.remove(req.getParameterMap());
                ObjectMapper om=new ObjectMapper();
                ResponseUtil.write(resp, om.writeValueAsString(remove));
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
            return null;
        }
    }

    前台代码,用layui框架规划显示的页面

      userManage.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="${pageContext.request.contextPath }/static/js/layui/css/layui.css">
    <script src="${pageContext.request.contextPath }/static/js/layui/layui.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery-3.3.1.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/userManage.js"></script>
    <title>书记类别管理</title>
    </head>
    <body class="child-body">
    <div class="child-nav">
        <span class="layui-breadcrumb">
             <a>书籍类别管理</a>
             <a><cite>分类列表</cite></a>
        </span>
    </div>
    <blockquote class="layui-elem-quote">
    
    <!--搜索维度  -->
     <div class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label">书籍名称</label>
            <div class="layui-input-inline">
                <input type="text" id="book_category_name" name="book_category_name" lay-verify="required" placeholder="请输入书籍名" autocomplete="true" class="layui-input">
            </div>
            <button class="layui-btn layui-btn-normal layui-btn-radius" data-type="reload"><i class="layui-icon">&#xe615;</i>查询</button>
            <button class="layui-btn layui-btn-normal"   data-type="add">新建</button>
        </div>
    </div>   
    </blockquote>
    
    <!--隐藏域传值  -->
    <input type="hidden"  id="ht" value="${pageContext.request.contextPath}" >
    <!--根据table id 来展示表格数据  -->
    <table class="layui-hide" id="test" lay-filter="test"></table>
    
    <!--行内样式按钮   -->
    <script type="text/html" id="lineBtns">
      <a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon">&#xe642;</i>编辑</a>
      <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>
    
    
    <!--弹出层  -->
         <div class="site-text" style="margin: 5%; display: none" id="bt"  target="test123">
            <form class="layui-form layui-form-pane" onsubmit="return false" id="booktype">
                <div class="layui-form-item">
                   <label class="layui-form-label">类型编号</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input layui-disabled text_add "  id="book_category_id" name="book_category_id"  disabled="disabled">
                    </div>
                    <br>
                    <label class="layui-form-label">书本类别名</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input"  id="book_category_name"  name="book_category_name"><br>
                    </div>
                </div>
            </form>
        </div> 
    </body>
    </html>

     userManage.js

      处理从后台传来的数据,并且根据前端代码进行展示

    //执行渲染
    layui.use(['table','layer','form'],function(){
        var data=document.getElementById("ht").value;
        var table =layui.table;
        var layer=layui.layer;
        var form = layui.form;
         /*展示数据表格  */
        table.render({
              elem:'#test'//表格id
            ,url:data+'/booktypeaction.action?methodName=select'//所对应调用的接口
            ,method:'post'        //提交方式
            ,cols:[[
                /*根据数据库的表格所对应的名称  */
                 {field:'book_category_id',height:80, 300, title: '书籍类别序号', sort: true}
                 ,{field:'book_category_name', height:80,300, title: '书籍类别名称'}
                 ,{field:'createtime',height:80, 300, title: '当前时间',templet:"<div>{{layui.util.toDateString(d.createtime, 'yyyy-MM-dd HH:mm:ss')}}</div>"}
                 ,{field:'right',height:80, 300, title: '操作', toolbar:'#lineBtns'}//操作栏 
            ]]
                 ,page:'true'//分页
                 , id: 'testReload'
        });
        
        //上方菜单操作栏(查询、以及  增加  按钮  )
        var $ = layui.$, active = {
                //查询
                reload: function () {
                    var book_category_name = $('#book_category_name');//书籍类别名称 根据 id来取值
                    console.log(booktypename.val());
                    // 执行重载
                    table.reload('testReload', {
                        page: {
                            curr: 1
                            // 重新从第 1 页开始
                        },
                        where: {
                            key: 'book_category_name',
                            book_category_name: book_category_name.val(),
                        }
                    });
                }, add: function () { //添加
                    layer.open({//弹出框
                        type: 1,
                        title: '添加书本类别',
                        maxmin: true,
                        shadeClose: true, //点击遮罩关闭层
                        area: ['80%', '80%'],
                        content: $('#box1'),
                        btn: ['确定', '取消'],
                        yes: function (index, layero) {//确定执行函数
                            console.log(layero);
                            //执行添加方法
                            $.getJSON(data+"/booktypeaction.action?methodName=add", {
                                 booktypename: $("#book_category_name").val(), //书本类型名称
                            }, function (data) {
                                /*根据后台返回的参数来进行判断  */
                                if (data==1) {
                                    layer.alert('添加成功', {icon: 1, title: '提示'}, function (i) {
                                        layer.close(i);
                                        layer.close(index);//关闭弹出层
                                        $("#booktype")[0].reset()//重置form
                                    })
                                    table.reload('testReload', {//重载表格
                                        page: {
                                            curr: 1
                                            // 重新从第 1 页开始
                                        }
                                    })
                                } else if(data==2){
                                    layer.msg('添加失败,请勿重复添加书本类别名称')
                                }
                            })
    
                        }, cancel: function (index, layero) {//取消
                            $("#booktype")[0].reset()//重置form  根据id
                            layer.close(index)
                        }
                    });
                }
        }
        $('.layui-form .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
        
        
        
        /*表格 行内操作(编辑  以及  删除 按钮操作)  */
            table.on('tool(test)', function(obj){
             var data = obj.data; //获得当前行数据
             var urlex=document.getElementById("ht").value;
             var tr=obj.tr//活动当前行tr 的  DOM对象
             console.log(data);
             var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
             if(layEvent === 'del'){ //删除
                 layer.confirm('确定删除吗?',{title:'删除'}, function(index){
                     //向服务端发送删除指令og
                     $.getJSON(urlex+'/booktypeaction.action?methodName=del',{book_category_id:data.book_category_id}, function(ret){
                             layer.close(index);//关闭弹窗
                             table.reload('testReload', {//重载表格
                                 page: {
                                     curr: 1
                                     // 重新从第 1 页开始
                                 }
                             })
                     });
                     layer.close(index);
                 });
             } else if(layEvent === 'edit'){ //编辑
                 layer.open({
                     type: 1 //Page层类型
                     ,skin: 'layui-layer-molv'
                     ,area: ['380px', '270px']
                     ,title: ['编辑书本类别信息','font-size:18px']
                     ,btn: ['确定', '取消'] 
                     ,shadeClose: true
                     ,shade: 0 //遮罩透明度
                     ,maxmin: true //允许全屏最小化
                     ,content:$('#bt')  //弹窗id
                     ,success:function(layero,index){
                         $('#book_category_id').val(data.book_category_id);
                         $('#book_category_name').val(data.book_category_name);  
                     },yes:function(index,layero){
                        /*  $.ajaxSettings.async = false; */
                          $.getJSON(urlex+'/booktypeAction.action?methodName=edit',{
                              book_category_id: $('#book_category_id').val(),
                              book_category_name: $('#book_category_name').val(), 
                              book_category_id: data.book_category_id,
                          },function(data){
                          //根据后台返回的参数,来进行判断
                              if(data>0){
                                  layer.alert('编辑成功',{icon:1,title:'提示'},function(i){
                                      layer.close(i);
                                      layer.close(index);//关闭弹出层
                                      $("#booktype")[0].reset()//重置form
                                  })
                                  table.reload('testReload',{//重载表格
                                      page:{
                                          curr:1
                                      }
                                  })
                              }
                          });
                     }
                   
                 
                 });
             }
          
            });
          
    });
    /**
     * 顶部搜索框 模糊查询
     * @returns
     *//*
    function dingselect(){
        var  select = $('#ks').val();
        $("#dg").datagrid({
            url : $("#txc").val()+'/booktypeaction.action?methodName=select&book_category_name='+select,
        })
    }*/
    /**
     * 查询增删改方法
     * @returns
     *//*
    function userManage(){    
        var url = "booktypeaction.action?methodName="+$("#xm").attr("data");
        $('#ff').form('submit', {   
            url:url,    
            success: function(param){    
                $('#dd').dialog('close');
                $('#dg').datagrid('reload');
                $('#ff').form('clear');
            }    
        });  
    }
    *//**
     * 修改方法
     * @returns
     *//*
    function edit(){
        var row = $('#dg').datagrid('getSelected');
        if(row){
            $('#ff').form('load', row);
            $('#dd').dialog('open');
            $('#xm').html('编辑');
            $('#xm').attr("data","edit");
        }
    }
    *//**
     * 新增方法
     * @returns
     *//*
    function add(){
        $('#ff').form('clear');
        $('#dd').dialog('open');
        $('#xm').html('新增');
        $('#xm').attr("data","add");
    }
    *//**
     * 删除方法
     * @returns
     *//*
    function remove(){
        var data=$('#dg').datagrid('getSelected');
        $.ajax({
            url : $("#txc").val()+'/booktypeaction.action?methodName=remove&book_category_id='+data.book_category_id,
            success: function(param){    
                $('#dg').datagrid('reload');
                }    
        })
    }*/

    配置xml

    <action path="/booktypeaction" type="com.ht.web.BooktypeAction">
            <forward name="index" path="/index.jsp" redirect="false" />
            <forward name="userManage" path="/userManage.jsp" redirect="false" />
        </action>

    今天的分享到此结束,谢谢观看!

  • 相关阅读:
    1033 To Fill or Not to Fill (25分)(贪心)
    CentOS(五)--Linux系统的分区概念
    Linux安装Oracle 11G过程(测试未写完)
    【VMware虚拟化解决方案】设计和配置VMware vCenter 5.5
    CentOS(四)--Linux系统的启动级别
    CentOS(三)--初识linux的文件系统以及用户组等概念
    CentOS(二)--初识linux的一些常用命令
    CentOS(一)--CentOS6.4环境搭建
    Linux c/c++图片传输功能(中级版)
    remote uptime 服务器程序
  • 原文地址:https://www.cnblogs.com/huangting/p/11161464.html
Copyright © 2011-2022 走看看