Rumah > hujung hadapan web > Tutorial Layui > 如何利用layui实现增删查改操作

如何利用layui实现增删查改操作

王林
Lepaskan: 2020-09-28 17:37:35
ke hadapan
4287 orang telah melayarinya

如何利用layui实现增删查改操作

首先认识layui

layui(谐音:类UI) 是一款采用自身模块规范编写的前端 UI 框架,遵循原生 HTML/CSS/JS 的书写与组织形式,门槛极低,拿来即用。其外在极简,却又不失饱满的内在,体积轻盈,组件丰盈,从核心代码到 API 的每一处细节都经过精心雕琢,非常适合界面的快速开发。

(推荐教程:layui

下载之后导进css、js样式

简单的效果图

92aecac704d751acb587c28cb2a1746.png

接下来直接上代码

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 &#39;%"+tname+"%&#39;";
		}
		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);
	}
	
	

}
Salin selepas log masuk

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 + "]";
	}

}
Salin selepas log masuk

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;
	}
	
	
	
	
}
Salin selepas log masuk

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>
Salin selepas log masuk

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>
Salin selepas log masuk

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=&#39;booktypename&#39; 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">&#xe615;</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">&#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="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([&#39;table&#39;,&#39;layer&#39;,&#39;form&#39;],function(){
	var data=document.getElementById("sj").value;
	var table =layui.table;
	var layer=layui.layer;
	var form = layui.form;
     /*展示数据表格  */
	table.render({
		  elem:&#39;#test&#39;//表格id
		,url:data+&#39;/booktypeAction.action?methodName=list&#39;//所对应调用的接口
		,method:&#39;post&#39;		//提交方式
	    ,cols:[[
	    	/*根据数据库的表格所对应的名称  */
	         {field:&#39;tid&#39;,height:80, width:300, title: &#39;书籍类别序号&#39;, sort: true}
	         ,{field:&#39;tname&#39;, height:80,width:300, title: &#39;书籍类别名称&#39;}
	         ,{field:&#39;right&#39;,height:80, width:300, title: &#39;操作&#39;, toolbar:&#39;#lineBtns&#39;}//操作栏 
	    ]]
	         ,page:&#39;true&#39;//分页
	         , id: &#39;testReload&#39;
	});
	
	//上方菜单操作栏(查询、以及  增加  按钮  )
    var $ = layui.$, active = {
            //查询
            reload: function () {
                var booktypename = $(&#39;#booktypename&#39;);//书籍类别名称 根据 id来取值
                console.log(booktypename.val());
                // 执行重载
                table.reload(&#39;testReload&#39;, {
                    page: {
                        curr: 1
                        // 重新从第 1 页开始
                    },
                    where: {
                        key: &#39;tname&#39;,
                        tname: booktypename.val(),
                    }
                });
            }, add: function () { //添加
                layer.open({//弹出框
                    type: 1,
                    title: &#39;添加书本类别&#39;,
                    maxmin: true,
                    shadeClose: true, //点击遮罩关闭层
                    area: [&#39;80%&#39;, &#39;80%&#39;],
                    content: $(&#39;#box1&#39;),
                    btn: [&#39;确定&#39;, &#39;取消&#39;],
                    yes: function (index, layero) {//确定执行函数
                    	console.log(layero);
                        //执行添加方法
                        $.getJSON(data+"/booktypeAction.action?methodName=addBookType", {
                        	tname: $("#booktypename1").val(), ///角色名
                        	/* booktypename: $("input[ name=&#39;booktypename1&#39;]").val(), *///角色名
                        }, function (data) {
                        	/*根据后台返回的参数来进行判断  */
                            if (data==1) {
                                layer.alert(&#39;添加成功&#39;, {icon: 1, title: &#39;提示&#39;}, function (i) {
                                    layer.close(i);
                                    layer.close(index);//关闭弹出层
                                    $("#booktype")[0].reset()//重置form
                                })
                                table.reload(&#39;testReload&#39;, {//重载表格
                                    page: {
                                        curr: 1
                                        // 重新从第 1 页开始
                                    }
                                })
                            } else if(data==2){
                                layer.msg(&#39;添加失败,请勿重复添加书本类别名称&#39;)
                            }
                        })

                    }, cancel: function (index, layero) {//取消
                        $("#booktype")[0].reset()//重置form  根据id
                        layer.close(index)
                    }
                });
            }
    }
    $(&#39;.layui-form .layui-btn&#39;).on(&#39;click&#39;, function () {
        var type = $(this).data(&#39;type&#39;);
        active[type] ? active[type].call(this) : &#39;&#39;;
    });
	
	
	
	/*表格 行内操作(编辑  以及  删除 按钮操作)  */
	    table.on(&#39;tool(test)&#39;, 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 === &#39;del&#39;){ //删除
             layer.confirm(&#39;确定删除吗?&#39;,{title:&#39;删除&#39;}, function(index){
                 //向服务端发送删除指令og
                 $.getJSON(urlex+&#39;/booktypeAction.action?methodName=deleteBookType&#39;,{tid:data.tid}, function(ret){
                         layer.close(index);//关闭弹窗
                         table.reload(&#39;testReload&#39;, {//重载表格
                             page: {
                                 curr: 1
                                 // 重新从第 1 页开始
                             }
                         })
                 });
                 layer.close(index);
             });
         } else if(layEvent === &#39;edit&#39;){ //编辑
             layer.open({
                 type: 1 //Page层类型
                 ,skin: &#39;layui-layer-molv&#39;
                 ,area: [&#39;380px&#39;, &#39;270px&#39;]
                 ,title: [&#39;编辑书本类别信息&#39;,&#39;font-size:18px&#39;]
                 ,btn: [&#39;确定&#39;, &#39;取消&#39;] 
                 ,shadeClose: true
                 ,shade: 0 //遮罩透明度
                 ,maxmin: true //允许全屏最小化
                 ,content:$(&#39;#box1&#39;)  //弹窗id
                 ,success:function(layero,index){
	                 $(&#39;#booktypeid&#39;).val(data.tid);
	                 $(&#39;#booktypename1&#39;).val(data.tname);  
                 },yes:function(index,layero){
                	/*  $.ajaxSettings.async = false; */
                	  $.getJSON(urlex+&#39;/booktypeAction.action?methodName=updateBookType&#39;,{
                		 tid: $(&#39;#booktypeid&#39;).val(),
                		  tname: $(&#39;#booktypename1&#39;).val(), 
                         tid: data.tid,
                	  },function(data){
                	  //根据后台返回的参数,来进行判断
                		  if(data>0){
                			  layer.alert(&#39;编辑成功&#39;,{icon:1,title:&#39;提示&#39;},function(i){
                				  layer.close(i);
                                  layer.close(index);//关闭弹出层
                                  $("#booktype")[0].reset()//重置form
                			  })
                			  table.reload(&#39;testReload&#39;,{//重载表格
                				  page:{
                					  curr:1
                				  }
                			  })
                		  }
                	  });
                 }
               
             
             });
         }
      
	    });
	  
});


// 实现查询所有的菜单

</script>

</html>
Salin selepas log masuk

本次所用到的jar包

7bd84aaee4bc0d604b9f4e6bd3302a9.png

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: &#39;#demo&#39;,// 传入元素选择器
                nodes: data,
//		     	spread:true,
                click: function (node) {// 点击tree菜单项的时候
                    var element = layui.element;
                    var exist = $("li[lay-id=&#39;" + node.id + "&#39;]").length;//判断是不是用重复的选项卡
                    if (exist > 0) {
                        element.tabChange(&#39;tabs&#39;, node.id);// 切换到已有的选项卡
                    } else {
                        if (node.attributes.menuURL != null && node.attributes.menuURL != "") {// 判断是否需要新增选项卡
                            element.tabAdd(
                                &#39;tabs&#39;,
                                {
                                    title: node.name,
                                    content: &#39;<iframe   scrolling="yes" frameborder="0" src=" &#39;
                                    + node.attributes.menuURL
                                    + &#39; " width="100%" height="100%"></iframe>&#39;// 支持传入html
                                    ,
                                    // width="99%" height="99%"
                                    id: node.id
                                });
                            element.tabChange(&#39;tabs&#39;, node.id);
                        }
                    }

                }

            });

        }

    });
})
Salin selepas log masuk

完成!

Atas ialah kandungan terperinci 如何利用layui实现增删查改操作. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:csdn.net
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan