如何利用layui实现增删查改操作
首先认识layui
layui(谐音:类UI) 是一款采用自身模块规范编写的前端 UI 框架,遵循原生 HTML/CSS/JS 的书写与组织形式,门槛极低,拿来即用。其外在极简,却又不失饱满的内在,体积轻盈,组件丰盈,从核心代码到 API 的每一处细节都经过精心雕琢,非常适合界面的快速开发。
(推荐教程:layui)
下载之后导进css、js样式
简单的效果图
接下来直接上代码
dao方法
package com.chen.dao; import java.sql.SQLException; import java.util.List; import java.util.Map; import com.chen.util.JsonBaseDao; import com.chen.util.JsonUtils; import com.chen.util.PageBean; import com.chen.util.StringUtils; public class BooktypeDao extends JsonBaseDao{ /** * 书籍类别查询 * @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_type where true"; String tid=JsonUtils.getParamVal(paMap, "tid"); String tname=JsonUtils.getParamVal(paMap, "tname"); if(StringUtils.isNotBlank(tid)) { sql+=" and tid ="+tid+" "; } if(StringUtils.isNotBlank(tname)) { sql+=" and tname like '%"+tname+"%'"; } sql += " order by tid desc "; return executeQuery(sql, pageBean); } /** * 增加 * @param paMap * @return * @throws NoSuchFieldException * @throws SecurityException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws SQLException */ public int addType(Map<String, String[]> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException { String sql="insert into t_type(tname) values(?) "; return super.executeUpdate(sql, new String[] {"tname"}, paMap); } /** * 修改 * @param paMap * @return * @throws NoSuchFieldException * @throws SecurityException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws SQLException */ public int editType(Map<String, String[]> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException { String sql="update t_type set tname=? where tid=?"; return super.executeUpdate(sql, new String[] {"tname","tid"}, paMap); } /** * 删除 * @param paMap * @return * @throws NoSuchFieldException * @throws SecurityException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws SQLException */ public int removeType(Map<String, String[]> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException { String sql="delete from t_type where tid=? "; return super.executeUpdate(sql, new String[] {"tid"}, paMap); } }
entity一个树形的实体类
package com.chen.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 + "]"; } }
action子控制器
package com.liuting.web; import java.sql.SQLException; 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.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.chen.dao.BooktypeDao; import com.chen.framework.ActionSupport; import com.chen.util.PageBean; import com.chen.util.ResponseUtil; public class BooktypeAction extends ActionSupport { private BooktypeDao booktypeDao=new BooktypeDao(); /** * 查询书籍类别 * @param req * @param resp * @return * @throws Exception */ public String list(HttpServletRequest req,HttpServletResponse resp) throws Exception { try { PageBean pageBean=new PageBean(); pageBean.setRequest(req); List<Map<String, Object>> list = this.booktypeDao.list(req.getParameterMap(), pageBean); ObjectMapper om =new ObjectMapper(); Map<String, Object> map=new HashMap<>(); map.put("code", 0); map.put("count", pageBean.getTotal()); map.put("data", list); ResponseUtil.write(resp, om.writeValueAsString(map)); } catch (InstantiationException e) { e.printStackTrace(); } return null; } /** * 增加 * @param req * @param resp * @return */ public String addBookType(HttpServletRequest req,HttpServletResponse resp) { try { List<Map<String, Object>> list = this.booktypeDao.list(req.getParameterMap(), null); int val = 0; //如果集合不为空 或者长度等于 0 就把它增加进去 if(list==null || list.size() == 0) { val = this.booktypeDao.addType(req.getParameterMap()); } else { val= 2; } ResponseUtil.write(resp, val); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 删除书本类别 * @throws Exception * @throws JsonProcessingException * */ public String deleteBookType(HttpServletRequest req,HttpServletResponse resp) throws JsonProcessingException, Exception { try { int deleteBookType=this.booktypeDao.removeType(req.getParameterMap()); ObjectMapper om=new ObjectMapper(); ResponseUtil.write(resp, om.writeValueAsString(deleteBookType)); } catch (NoSuchFieldException e) { e.printStackTrace(); } return null; } /** * 修改书籍类别 * @param req * @param resp * @return * @throws JsonProcessingException * @throws Exception */ public String updateBookType(HttpServletRequest req,HttpServletResponse resp) throws JsonProcessingException, Exception { try { int updateBookType=this.booktypeDao.editType(req.getParameterMap()); ObjectMapper om=new ObjectMapper(); ResponseUtil.write(resp, om.writeValueAsString(updateBookType)); } catch (NoSuchFieldException e) { e.printStackTrace(); } return null; } /** * 下拉框 */ public String listSelect(HttpServletRequest req,HttpServletResponse resp) throws Exception { try { PageBean pageBean=new PageBean(); pageBean.setRequest(req); List<Map<String, Object>> list = this.booktypeDao.list(req.getParameterMap(), pageBean); ObjectMapper om =new ObjectMapper(); ResponseUtil.write(resp, om.writeValueAsString(list)); } catch (InstantiationException e) { e.printStackTrace(); } return null; } }
mvc.xml的配置路径
<?xml version="1.0" encoding="UTF-8"?> <config> <action path="/booktypeAction" type="com.chen.web.BooktypeAction"> <forward name="index" path="/xz.jsp" redirect="false" /> <forward name="addBookType" path="/add.jsp" redirect="true" /> </action> <action path="/menuAction" type="com.chen.web.MenuAction"> <forward name="index" path="/index.jsp" redirect="false" /> </action> <action path="/userAction" type="com.chen.web.UserAction"> <forward name="index" path="/index.jsp" redirect="false" /> </action> <!--书本信息 --> <action path="/bookAction" type="com.chen.web.BookAction"> <forward name="index" path="/index.jsp" redirect="false" /> <forward name="addBookType" path="/add.jsp" redirect="true" /> </action> </config>
web.xml的配置路径
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>Mvc_Layui</display-name> <filter> <filter-name>encodingFiter</filter-name> <filter-class>com.chen.util.EncodingFiter</filter-class> </filter> <filter-mapping> <filter-name>encodingFiter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>dispatherServlet</servlet-name> <servlet-class>com.chen.framework.DispatherServlet</servlet-class> <init-param> <param-name>xmlPath</param-name> <param-value>/mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatherServlet</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> </web-app>
jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="/jsp/common/head.jsp" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</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='booktypename' name="booktypename" 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"></i>查询</button> <button class="layui-btn layui-btn-normal" data-type="add">新建</button> </div> </div> </blockquote> <!--隐藏域传值 --> <input type="hidden" id="sj" 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"></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="box1" 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="booktypeid" name=booktypeid disabled="disabled"> </div> <br> <label class="layui-form-label"> 书本类别名</label> <div class="layui-input-block"> <input type="text" class="layui-input" id="booktypename1" name=booktypename1><br> </div> </div> </form> </div> </body> <!--权限--> <script > //管理 //执行渲染 layui.use(['table','layer','form'],function(){ var data=document.getElementById("sj").value; var table =layui.table; var layer=layui.layer; var form = layui.form; /*展示数据表格 */ table.render({ elem:'#test'//表格id ,url:data+'/booktypeAction.action?methodName=list'//所对应调用的接口 ,method:'post' //提交方式 ,cols:[[ /*根据数据库的表格所对应的名称 */ {field:'tid',height:80, width:300, title: '书籍类别序号', sort: true} ,{field:'tname', height:80,width:300, title: '书籍类别名称'} ,{field:'right',height:80, width:300, title: '操作', toolbar:'#lineBtns'}//操作栏 ]] ,page:'true'//分页 , id: 'testReload' }); //上方菜单操作栏(查询、以及 增加 按钮 ) var $ = layui.$, active = { //查询 reload: function () { var booktypename = $('#booktypename');//书籍类别名称 根据 id来取值 console.log(booktypename.val()); // 执行重载 table.reload('testReload', { page: { curr: 1 // 重新从第 1 页开始 }, where: { key: 'tname', tname: booktypename.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=addBookType", { tname: $("#booktypename1").val(), ///角色名 /* booktypename: $("input[ name='booktypename1']").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("sj").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=deleteBookType',{tid:data.tid}, 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:$('#box1') //弹窗id ,success:function(layero,index){ $('#booktypeid').val(data.tid); $('#booktypename1').val(data.tname); },yes:function(index,layero){ /* $.ajaxSettings.async = false; */ $.getJSON(urlex+'/booktypeAction.action?methodName=updateBookType',{ tid: $('#booktypeid').val(), tname: $('#booktypename1').val(), tid: data.tid, },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 } }) } }); } }); } }); }); // 实现查询所有的菜单 </script> </html>
本次所用到的jar包
index.js
$(function () { $.ajax({ type: "post", url: "menuAction.action?methodName=treeMenu", dataType: "json", /*data: {// 传给servlet的数据, role_id: MenuHid, right_code: "-1", d: new Date() },*/ success: function (data) { console.info(data); layui.tree({ elem: '#demo',// 传入元素选择器 nodes: data, // spread:true, click: function (node) {// 点击tree菜单项的时候 var element = layui.element; var exist = $("li[lay-id='" + node.id + "']").length;//判断是不是用重复的选项卡 if (exist > 0) { element.tabChange('tabs', node.id);// 切换到已有的选项卡 } else { if (node.attributes.menuURL != null && node.attributes.menuURL != "") {// 判断是否需要新增选项卡 element.tabAdd( 'tabs', { title: node.name, content: '<iframe scrolling="yes" frameborder="0" src=" ' + node.attributes.menuURL + ' " width="100%" height="100%"></iframe>'// 支持传入html , // width="99%" height="99%" id: node.id }); element.tabChange('tabs', node.id); } } } }); } }); })
完成!
以上就是如何利用layui实现增删查改操作的详细内容,更多请关注www.sxiaw.com其它相关文章!