您好,登錄后才能下訂單哦!
小編給大家分享一下怎么利用layui實現增刪查改操作,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
首先認識layui
layui(諧音:類UI) 是一款采用自身模塊規范編寫的前端 UI 框架,遵循原生 HTML/CSS/JS 的書寫與組織形式,門檻極低,拿來即用。其外在極簡,卻又不失飽滿的內在,體積輕盈,組件豐盈,從核心代碼到 API 的每一處細節都經過精心雕琢,非常適合界面的快速開發。
下載之后導進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實現增刪查改操作的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。