


How to use layui to implement add, delete, check and modify operations
First get to know layui
layui (homophone: UI-like) is a front-end UI framework written using its own module specifications, following native HTML/CSS/ JS's writing and organizational form has a very low threshold and is ready to use. It is minimalist on the outside but full on the inside. It is light in size and rich in components. Every detail from the core code to the API has been carefully crafted, making it very suitable for rapid interface development.
(Recommended tutorial: layui)
Import css and js styles after downloading
Simple renderings
Next go directly to the code
dao method
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 is a tree-shaped entity class
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 sub-controller
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 configuration path
<?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 configuration path
<?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
<%@ 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>
The jar package used this time
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); } } } }); } }); })
Done!
The above is the detailed content of How to use layui to implement add, delete, check and modify operations. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Layui login page jump setting steps: Add jump code: Add judgment in the login form submit button click event, and jump to the specified page through window.location.href after successful login. Modify the form configuration: add a hidden input field to the form element of lay-filter="login", with the name "redirect" and the value being the target page address.

layui provides a variety of methods for obtaining form data, including directly obtaining all field data of the form, obtaining the value of a single form element, using the formAPI.getVal() method to obtain the specified field value, serializing the form data and using it as an AJAX request parameter, and listening Form submission event gets data.

Adaptive layout can be achieved by using the responsive layout function of the layui framework. The steps include: referencing the layui framework. Define an adaptive layout container and set the layui-container class. Use responsive breakpoints (xs/sm/md/lg) to hide elements under specific breakpoints. Specify element width using the grid system (layui-col-). Create spacing via offset (layui-offset-). Use responsive utilities (layui-invisible/show/block/inline) to control the visibility of elements and how they appear.

The difference between layui and Vue is mainly reflected in functions and concerns. Layui focuses on rapid development of UI elements and provides prefabricated components to simplify page construction; Vue is a full-stack framework that focuses on data binding, component development and state management, and is more suitable for building complex applications. Layui is easy to learn and suitable for quickly building pages; Vue has a steep learning curve but helps build scalable and easy-to-maintain applications. Depending on the project needs and developer skill level, the appropriate framework can be selected.

The method of using layui to transmit data is as follows: Use Ajax: Create the request object, set the request parameters (URL, method, data), and process the response. Use built-in methods: Simplify data transfer using built-in methods such as $.post, $.get, $.postJSON, or $.getJSON.

layui is a front-end UI framework that provides a wealth of UI components, tools and functions to help developers quickly build modern, responsive and interactive web applications. Its features include: flexible and lightweight, modular design, rich components, Powerful tools and easy customization. It is widely used in the development of various web applications, including management systems, e-commerce platforms, content management systems, social networks and mobile applications.

layui and vue are front-end frameworks. layui is a lightweight library that provides UI components and tools; vue is a comprehensive framework that provides UI components, state management, data binding, routing and other functions. layui is based on a modular architecture, and vue is based on a componentized architecture. layui has a smaller ecosystem, vue has a large and active ecosystem. The learning curve of layui is low, and the learning curve of vue is steep. Layui is suitable for small projects and rapid development of UI components, while vue is suitable for large projects and scenarios that require rich functions.

The layui framework is a JavaScript-based front-end framework that provides a set of easy-to-use UI components and tools to help developers quickly build responsive web applications. Its features include: modular, lightweight, responsive, and has complete documentation and community support. layui is widely used in the development of management backend systems, e-commerce websites, and mobile applications. The advantages are quick start-up, improved efficiency, and easy maintenance. The disadvantages are poor customization and slow technology updates.
