運用layui實現增刪改查
首先認識layui
layui(諧音:類UI) 是一款採用自身模組規範編寫的前端 UI 框架,遵循原生 HTML/CSS/JS 的書寫與組織形式,門檻極低,拿來即用。其外在極簡,卻又不失飽滿的內在,體積輕盈,元件豐盈,從核心程式碼到 API 的每一處細節都經過精心雕琢,非常適合介面的快速開發。
它的官方網址: https://www.layui.com/
下載之後導進css、js樣式
簡單的效果圖
接下來直接上程式碼
util的工具類什麼的,之前的部落格有寫到
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實現的增刪改完成啦
相關文章
- layui的增刪改查UI
- Jfinal+layui增刪改查UI
- Layui(4) 增刪改查 完整案例UI
- layui+ssm簡單增刪改查UISSM
- js實現表格的增刪改查JS
- 關於ToDolist 的增刪改查 用jQuery來實現jQuery
- 單連結串列實現增刪改查
- Go實現對MySQL的增刪改查GoMySql
- 增刪改查
- Node.js+Express+Mysql 實現增刪改查Node.jsExpressMySql
- Java實現簡單的增刪改查操作Java
- Mybatis-plus實現簡單增刪改查MyBatis
- jQuery實現購物車的增刪改查jQuery
- Entity Framework使用DBContext實現增刪改查示例FrameworkContext
- 封裝模組實現商品增刪改查封裝
- webpack4+express+mongodb+vue 實現增刪改查WebExpressMongoDBVue
- JDBC連線mysql-8.0實現增刪改查JDBCMySql
- python 連線mongodb實現增刪改查例項PythonMongoDB
- SpringMVC+Spring Data JPA實現增刪改查操作SpringMVC
- 第一個mybatis程式,實現增刪改查CRUDMyBatis
- 連線資料庫並實現增、刪、改、查資料庫
- JDBC連線資料庫實現增刪改查JDBC資料庫
- koa+mysql實現增刪改查-全棧之路MySql全棧
- IDEA SpringBoot-Mybatis-plus 實現增刪改查(CRUD)IdeaSpring BootMyBatis
- mybatis實現MySQL資料庫的增刪改查MyBatisMySql資料庫
- SQL增刪改查SQL
- Mongoose查增改刪Go
- indexedDB 增刪改查Index
- mysql增刪改查MySql
- SpringBoot+Mybatis增刪改查實戰Spring BootMyBatis
- Node+Vue實現對資料的增刪改查Vue
- 寫一個簡單的Linkedlist,實現增刪改查
- 使用express+mongoose對mongodb實現增刪改查操作ExpressMongoDB
- 使用Mongoose類庫實現簡單的增刪改查Go
- express+mongodb+vue實現增刪改查-全棧之路ExpressMongoDBVue全棧
- 列表的增刪改查
- 字典的增刪改查
- mongodb 基本增刪改查MongoDB