maven與layUI的權限設計
項目介紹
這次項目主要做的就是學會使用layUI做一個權限,可以適應於多個權限的使用,這裏主要是3個角色,用戶,角色,和菜單,實現多對多的關係,有兩個中間的媒介,直接將表展示出來吧!
/*
MySQL Data Transfer
Source Host: localhost
Source Database: t_hgy
Target Host: localhost
Target Database: t_hgy
Date: 2019/7/10 ������ 23:27:12
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for part
-- ----------------------------
DROP TABLE IF EXISTS `part`;
CREATE TABLE `part` (
`part_id` int(20) NOT NULL AUTO_INCREMENT COMMENT '標識列,自增',
`part_name` varchar(150) NOT NULL COMMENT '角色名',
`description` varchar(255) DEFAULT NULL COMMENT '說明',
`statu` int(255) DEFAULT '1' COMMENT '角色狀態(1可以2不可用)',
PRIMARY KEY (`part_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT;
-- ----------------------------
-- Table structure for part_and_permission
-- ----------------------------
DROP TABLE IF EXISTS `part_and_permission`;
CREATE TABLE `part_and_permission` (
`part_id` bigint(20) NOT NULL COMMENT '角色id',
`permission_id` bigint(20) NOT NULL COMMENT '菜單id'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT;
-- ----------------------------
-- Table structure for permission
-- ----------------------------
DROP TABLE IF EXISTS `permission`;
CREATE TABLE `permission` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '菜單id',
`name` varchar(255) DEFAULT NULL COMMENT '菜單名',
`url` varchar(255) DEFAULT NULL COMMENT '跳轉路徑',
`pId` bigint(20) DEFAULT NULL COMMENT '父節點id',
`type` int(255) DEFAULT NULL COMMENT '菜單類型 1菜單 2按鈕',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT;
-- ----------------------------
-- Table structure for t_clazz
-- ----------------------------
DROP TABLE IF EXISTS `t_clazz`;
CREATE TABLE `t_clazz` (
`cid` int(11) NOT NULL AUTO_INCREMENT,
`cname` varchar(255) DEFAULT NULL,
`cteachar` varchar(255) DEFAULT NULL,
`pic` varchar(255) DEFAULT NULL,
PRIMARY KEY (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`user_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '標識列,自增',
`user_name` varchar(255) NOT NULL COMMENT '名稱',
`pwd` varchar(255) NOT NULL COMMENT '密碼',
`statu` bigint(255) NOT NULL DEFAULT '1' COMMENT '默認爲1即可用,0爲不可用',
PRIMARY KEY (`user_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT;
-- ----------------------------
-- Table structure for user_and_part
-- ----------------------------
DROP TABLE IF EXISTS `user_and_part`;
CREATE TABLE `user_and_part` (
`user_id` bigint(20) NOT NULL COMMENT '管理人員id',
`part_id` bigint(20) NOT NULL COMMENT '角色id'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT;
-- ----------------------------
-- Records
-- ----------------------------
INSERT INTO `part` VALUES ('15', '普通用戶', '只能進行普通數據的管理,不能進行用戶和角色的管理', '1');
INSERT INTO `part` VALUES ('17', '超級管理員', '角色,用戶,普通數據的管理', '1');
INSERT INTO `part` VALUES ('19', '胡桂雲123', '愛的色放三', '0');
INSERT INTO `part_and_permission` VALUES ('17', '1');
INSERT INTO `part_and_permission` VALUES ('17', '2');
INSERT INTO `part_and_permission` VALUES ('17', '3');
INSERT INTO `part_and_permission` VALUES ('17', '4');
INSERT INTO `part_and_permission` VALUES ('17', '5');
INSERT INTO `part_and_permission` VALUES ('19', '4');
INSERT INTO `part_and_permission` VALUES ('19', '5');
INSERT INTO `part_and_permission` VALUES ('15', '4');
INSERT INTO `part_and_permission` VALUES ('15', '5');
INSERT INTO `permission` VALUES ('1', '權限管理', null, '0', '1');
INSERT INTO `permission` VALUES ('2', '用戶管理', '/userManagement.jsp', '1', '1');
INSERT INTO `permission` VALUES ('3', '角色管理', '/partManagement.jsp', '1', '1');
INSERT INTO `permission` VALUES ('4', '普通數據', null, '0', '1');
INSERT INTO `permission` VALUES ('5', '普通數據管理', '/Clazz.jsp', '4', '1');
INSERT INTO `t_clazz` VALUES ('1', 'T224', '李曉', '東方故事');
INSERT INTO `t_clazz` VALUES ('2', 'T225', '小四', '阿斯蒂芬');
INSERT INTO `t_clazz` VALUES ('3', 'T226', '李曉', '散打');
INSERT INTO `user` VALUES ('38', 'admin', '123', '1');
INSERT INTO `user` VALUES ('39', '胡桂雲', '123', '1');
INSERT INTO `user_and_part` VALUES ('38', '17');
INSERT INTO `user_and_part` VALUES ('39', '15');
目錄結構
這裏需要說一下那個formSelects-v3.js是layUI的一個插件,用戶界面角色下拉框
文件配置
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hu</groupId>
<artifactId>T224</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>T224 Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--servlet依賴 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- mySql 依賴 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<!-- 引用struts2框架核心依賴 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.5.16</version>
</dependency>
<!-- hutoll工具包 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.5.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
</dependencies>
<build>
<finalName>T224</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
wab.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>
<filter>
<filter-name>EncodingFiter</filter-name>
<filter-class>com.crud.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFiter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
</web-app>
前臺代碼
登錄的login.jsp 與login.js
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登錄</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/static/js/layui/css/layui.css" media="all">
<link rel="stylesheet" href="${pageContext.request.contextPath }/static/js/css/login.css">
<script src="${pageContext.request.contextPath }/static/js/layui/layui.all.js"></script>
<style>
video {
object-fit: fill;
width: 1420px;
height: 700px;
}
</style>
</head>
<body>
<input type="hidden" id="path" value="${pageContext.request.contextPath}">
<video class="video-player" preload="auto" autoplay="autoplay" loop="loop" data-height="1080"
width="1920">
<!---->
<source src="${pageContext.request.contextPath }/static/admin/mv.mp4" type="video/mp4">
</video>
<div class="video_mask"></div>
<div class="login">
<h1>管理員登錄</h1>
<form class="layui-form">
<div class="layui-form-item">
<input class="layui-input" id="user_name" name="user_name" placeholder="用戶名" value=""
lay-verify="required" lay-verType="tips" type="text" autocomplete="off">
</div>
<div class="layui-form-item">
<input class="layui-input" id="pwd" name="pwd" placeholder="密碼" value=""
lay-verify="required" lay-verType="tips" type="password" autocomplete="off">
</div>
<button class="layui-btn login_btn" lay-submit="" lay-filter="login">登錄</button>
</form>
</div>
<script src="${pageContext.request.contextPath }/static/js/login.js"></script>
</body>
</html>
login.js
layui.config({
base: "static/js/"
}).use(['form', 'layer'], function () {
var form = layui.form,
layer = parent.layer === undefined ? layui.layer : parent.layer,
$ = layui.jquery;
//獲取絕對路徑
var path = $("#path").val();
//登錄按鈕事件
form.on("submit(login)", function (data) {
// $.ajaxSettings.async = false;
$.post(path + "/sy/userAction_login.action", {
user_name: $('#user_name').val(),
pwd: $('#pwd').val()
}, function (data) {
console.log(data);
if (data > 0) {//登錄成功
layer.msg("登錄成功", {icon:1,time: 1000}, function () {
parent.location.href = path + '/index.jsp';
})
} else {
layer.msg("登錄失敗,帳號或密碼錯誤或帳號不可用", {icon:2,time: 1000}, function () {
})
}
})
return false;
})
});
function refreshCode() {
var captcha = document.getElementById("captcha");
captcha.src = "/captcha.jpg?t=" + new Date().getTime();
}
用戶管理和js
usermanagement.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet"
href="${pageContext.request.contextPath}/static/js/layui/css/layui.css"
media="all">
<script type="text/javascript"
src="${pageContext.request.contextPath}/static/js/jquery-3.3.1.js"></script>
<script type="text/javascript"
src="${pageContext.request.contextPath}/static/js/layui/layui.js"></script>
</head>
<body>
<input type="hidden" id="path"
value="${pageContext.request.contextPath}" />
<!--搜索維度-->
<div class="layui-form">
<div class="layui-form-item">
<label class="layui-form-label">用戶名</label>
<div class="layui-input-inline">
<input type="text" id='user_name' name="user_name"
lay-verify="required" placeholder="請輸入用戶名" autocomplete="true"
class="layui-input">
</div>
<label class="layui-form-label">角色</label>
<div class="layui-input-inline">
<select xm-select="user_part_id" xm-select-type="2"
id="user_part_id" xm-select-skin="primary">
</select>
</div>
<button class="layui-btn" data-type="reload">查詢</button>
<button class="layui-btn layui-btn-danger" data-type="add">新建</button>
</div>
</div>
<!--顯示數據的表格-->
<div class="demoTable">
<div class=layui-form>
<table class="layui-table" id="LAY_table_user" lay-filter="user"
lay-data="{id: 'idTest'}">
</table>
</div>
</div>
<!--彈出層-->
<div class="site-text" style="margin: 5%; display: none" id="box1"
target="test123">
<form method="post" class="layui-form layui-form-pane"
onsubmit="return false" id="users">
<div class="layui-form-item">
<label class="layui-form-label">用戶名</label>
<div class="layui-input-block">
<input type="text" class="layui-input text_add" id="user_names"
name=user_names>
</div>
<br> <label class="layui-form-label"> 用戶密碼</label>
<div class="layui-input-block">
<input type="password" class="layui-input" id="pwd" name=pwd><br>
</div>
</div>
<label class="layui-form-label">選擇角色</label>
<div class="layui-input-block">
<select xm-select="user_part_ids" xm-select-type="2"
id="user_part_ids" xm-select-skin="primary">
</select>
</div>
</form>
</div>
<!--按鈕菜單-->
<script type="text/html" id="barDemo">
{{# if(d.statu==0){ }}
<a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="begin">啓用</a>
<a class="layui-btn layui-btn-xs" lay-event="edit">編輯</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">刪除</a>
{{# }else{ }}
<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="end">禁用</a>
<a class="layui-btn layui-btn-xs" lay-event="edit">編輯</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">刪除</a>
{{# } }}
</script>
<script src="${pageContext.request.contextPath}/static/js/userManagement.js"></script>
</body>
</HTML>
usermanagement.js
var path = document.getElementById("path").value;
layui.config({
base : path + '/static/js/' // 此處寫的相對路徑, 實際以項目中的路徑爲準
}).extend({
formSelects : 'formSelects-v3'
});
// 用戶管理
layui
.use(
[ 'table', 'form', 'jquery', 'formSelects' ],
// , 'from'
function() {
var table = layui.table, form = layui.form, formSelects = layui.formSelects;
// 第一個實例
table.render({
elem : '#LAY_table_user',
// height: 300,
url : path + '/sy/userAction_query.action'// 數據接口
,
// defaultToolbar : [ 'filter', 'print', 'exports' ],
page : true // 開啓分頁
,
limit : 10,
limits : [ 5, 10, 15 ],
cellMinWidth : 80,
cols : [ [ {
field : 'user_id',
title : '編號',
sort : true,
// width: 80,
}, {
field : 'user_name',
title : '用戶名',
// width: 80,
}, {
field : 'part_names',
title : '角色',
// width: 180,
}, {
fixed : 'right',
title : '操作',
align : 'center',
toolbar : '#barDemo'
} ] ],
id : 'testReload',
});
table.on('checkbox(user)', function(obj) {
console.log(obj)
});
// 上方菜單
var $ = layui.$, active = {
// 查詢
reload : function() {
// 執行重載
table.reload('testReload', {
page : {
curr : 1
// 重新從第 1 頁開始
},
where : {
user_name : $('#user_name').val(),
part_ids : formSelects.value(
'user_part_id', 'valStr')
}
});
},
add : function() { // 添加
$('#user_names').prop('disabled', false)// 設置可用
$('#user_names').removeClass('layui-disabled')
layer.open({
type : 1,
title : '添加用戶',
maxmin : true,
shadeClose : true, // 點擊遮罩關閉層
area : [ '80%', '80%' ],
content : $('#box1'),
btn : [ '確定', '取消' ],
success : function(layero, index) {// 彈出後執行的函數
formSelects.value('user_part_ids', []);
},
yes : function(index, layero) {// 確定執行函數
// 執行添加方法
$.post(path
+ '/sy/userAction_add.action', {
user_name : $('#user_names').val(),// 用戶名
pwd : $('#pwd').val(),// 密碼
part_ids : formSelects.value(
"user_part_ids", 'valStr')
}, function(data) {
if (data > 0) {
layer.alert('添加成功', {
icon : 1,
title : '提示'
}, function(i) {
layer.close(i);
layer.close(index);// 關閉彈出層
$("#users")[0].reset()// 重置form
})
table.reload('testReload', {// 重載表格
page : {
curr : 1
// 重新從第 1 頁開始
}
})
} else if (data == -2) {
layer.msg('添加失敗,用戶名不能重複')
} else {
layer.msg('添加失敗')
}
})
},
cancel : function(index, layero) {
$("#users")[0].reset()// 重置form
layer.close(index)
}
});
}
}
$('.layui-form .layui-btn').on('click', function() {
var type = $(this).data('type');
active[type] ? active[type].call(this) : '';
});
// table菜單
table.on('tool(user)', function(obj) {
var data = obj.data;// 獲得當前行數據
var layEvent = obj.event; // 獲得 lay-event
// 對應的值(也可以是表頭的event參數對應的值)
var tr = obj.tr; // 獲得當前行 tr 的DOM對象
if (layEvent == 'edit') {// 編輯
layer.open({
type : 1,
title : '編輯用戶',
maxmin : true,
shadeClose : true, // 點擊遮罩關閉層
area : [ '80%', '80%' ],
content : $('#box1'),
btn : [ '確定', '取消' ],
success : function(layero, index) {// 彈出後執行的函數
$('#pwd').val(data.pwd);
$('#user_names').val(data.user_name);
formSelects.value('user_part_ids', []);
formSelects.value('user_part_ids',
data.part_ids.split(","));
},
yes : function(index, layero) {// 確定回調函數
$.ajaxSettings.async = false;
$.post(path
+ '/sy/userAction_edit.action', {
pwd : $('#pwd').val(),
user_id : data.user_id,
user_name : $("#user_names").val(),
part_ids : formSelects.value(
"user_part_ids", 'valStr')
}, function(data) {
if (data > 0) {
layer.alert('編輯成功', {
icon : 1,
title : '提示'
}, function(i) {
layer.close(i);
layer.close(index);// 關閉彈出層
$("#users")[0].reset()// 重置form
})
table.reload('testReload', {// 重載表格
page : {
curr : 1
// 重新從第 1 頁開始
}
})
} else if (data = -2) {
layer.msg('用戶名重複')
} else {
layer.msg('編輯失敗')
}
})
},
cancel : function(index, layero) {
$("#users")[0].reset()// 重置form
layer.close(index)
}
})
} else if (layEvent == 'begin') {// 啓用
layer.confirm('確定啓用嗎???', {
icon : 3,
title : '提示'
}, function(index) {
$.post(path
+ '/sy/userAction_eidtStatu.action', {
user_id : data.user_id,
statu : 1
}, function(data) {
layer.close(index);
table.reload('testReload', {
page : {
curr : 1
// 重新從第 1 頁開始
}
})
});
})
} else if (layEvent == 'end') {// end//禁用
layer.confirm('確定禁用嗎???', {
icon : 3,
title : '提示'
}, function(index) {
$.post(path
+ '/sy/userAction_eidtStatu.action', {
user_id : data.user_id,
statu : 0
}, function(data) {
layer.close(index);
table.reload('testReload', {
page : {
curr : 1
// 重新從第 1 頁開始
}
})
});
})
} else if (layEvent == 'del') {// 刪除
layer.confirm('確定刪除嗎???', {
icon : 3,
title : '提示'
}, function(index) {
$.post(
path + '/sy/userAction_remove.action',
{
user_id : data.user_id
}, function(data) {
layer.close(index);
table.reload('testReload', {
page : {
curr : 1
// 重新從第 1 頁開始
}
})
});
})
}
});
});
/**
* 搜索下拉框角色加載
*/
function part() {
$.ajaxSettings.async = false
$.getJSON(path + '/sy/partAction_select.action', {}, function(data) {
var html = "<option value=''>直接選擇或搜索選擇</option>";
// 返回處理的方法
$.each(data, function(index, item) {
html += "<option value=" + item.part_id + ">" + item.part_name
+ "</option>";
});
$('#user_part_id').html(html);
$('#user_part_ids').html(html);
})
}
part();
角色管理和js
partmanagement.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>角色管理</title>
<link rel="stylesheet"
href="${pageContext.request.contextPath}/static/js/layui/css/layui.css"
media="all">
<script type="text/javascript"
src="${pageContext.request.contextPath}/static/js/jquery-3.3.1.js"></script>
<script type="text/javascript"
src="${pageContext.request.contextPath}/static/js/layui/layui.js"></script>
<link rel="stylesheet"
href="${pageContext.request.contextPath}/static/zTree/css/metroStyle/metroStyle.css"
type="text/css">
<script type="text/javascript"
src="${pageContext.request.contextPath}/static/zTree/js/jquery.ztree.core.js"></script>
<script type="text/javascript"
src="${pageContext.request.contextPath}/static/zTree/js/jquery.ztree.excheck.js"></script>
</head>
<body>
<input type="hidden" id="path"
value="${pageContext.request.contextPath}">
<!--搜索維度-->
<div class="layui-form">
<div class="layui-form-item">
<label class="layui-form-label">角色名</label>
<div class="layui-input-inline">
<input type="text" id='part_name' name="part_name"
lay-verify="required" placeholder="請輸入角色名" autocomplete="true"
class="layui-input">
</div>
<button class="layui-btn" data-type="reload">查詢</button>
<button class="layui-btn layui-btn-danger" data-type="add">新建</button>
</div>
</div>
<!--顯示數據的表格-->
<div class="demoTable">
<div class=layui-form>
<table class="layui-table" id="LAY_table_user" lay-filter="user"
lay-data="{id: 'idTest'}">
</table>
</div>
</div>
<!--彈出層-->
<div class="site-text" style="margin: 5%; display: none" id="box1"
target="test123">
<form class="layui-form layui-form-pane" onsubmit="return false"
id="users">
<div class="layui-form-item">
<label class="layui-form-label">角色名</label>
<div class="layui-input-block">
<input type="text" class="layui-input" id="part_names"
name=part_names>
</div>
<br> <label class="layui-form-label"> 角色說明</label>
<div class="layui-input-block">
<input type="text" class="layui-input" id="description"
name=description><br>
</div>
</div>
</form>
</div>
<!--權限-->
<div class="site-text layui-form" style="margin: 5%; display: none"
id="box3" target="test1232">
<div class="content_wrap">
<div class="zTreeDemoBackground left">
<ul id="treeDemo" class="ztree"></ul>
</div>
<div class="right" style="display: none;">
<ul class="info">
<li class="title">
<ul class="list">
<li><input type="checkbox" id="py" class="checkbox first"
checked /> <input type="checkbox" id="sy"
class="checkbox first" checked /> <input type="checkbox"
id="pn" class="checkbox first" checked /> <input
type="checkbox" id="sn" class="checkbox first" checked /></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<!--按鈕菜單-->
<script type="text/html" id="barDemo">
{{# if(d.statu==0){ }}
<a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="begin">啓用</a>
<a class="layui-btn layui-btn-xs" lay-event="edit">編輯</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">刪除</a>
{{# }else{ }}
<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="end">禁用</a>
<a class="layui-btn layui-btn-xs" lay-event="edit">編輯</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">刪除</a>
<a class="layui-btn layui-btn-xs" lay-event="right">角色權限</a>
{{# } }}
</script>
<script src="${pageContext.request.contextPath}/static/js/partManagement.js"></script>
</body>
</html>
partmanagement.js
var path = document.getElementById("path").value;
// 角色管理
layui.use([ 'table', 'form' ],
// , 'from'
function() {
var table = layui.table;
// 第一個實例
table.render({
elem : '#LAY_table_user',
// height: 300,
url : path + '/sy/partAction_query.action',// 數據接口
// defaultToolbar : [ 'filter', 'print', 'exports' ],
page : true // 開啓分頁
,
limit : 10,
limits : [ 5, 10, 15 ],
cellMinWidth : 80,
cols : [ [ {
field : 'part_id',
title : '編號',
sort : true,
// width: 80,
}, {
field : 'part_name',
title : '角色名',
// width: 80,
}, {
field : 'description',
title : '角色說明',
}, {
fixed : 'right',
title : '操作',
align : 'center',
toolbar : '#barDemo'
} ] ],
id : 'testReload',
});
table.on('checkbox(user)', function(obj) {
console.log(obj)
});
// 上方菜單
var $ = layui.$, active = {
// 查詢
reload : function() {
var part_name = $('#part_name');// 角色名
// 執行重載
table.reload('testReload', {
page : {
curr : 1 // 重新從第 1 頁開始
},
where : {
key : 'part_name',
part_name : part_name.val(),
}
});
},
add : function() { // 添加
layer.open({
type : 1,
title : '添加角色',
maxmin : true,
shadeClose : true, // 點擊遮罩關閉層
area : [ '80%', '80%' ],
content : $('#box1'),
btn : [ '確定', '取消' ],
yes : function(index, layero) {// 確定執行函數
// 執行添加方法
$.post(path + '/sy/partAction_add.action', {
part_name : $('#part_names').val(),// 角色名
description : $('#description').val(),// 角色說明
}, function(data) {
if (data > 0) {
layer.alert('添加成功', {
icon : 1,
title : '提示'
}, function(i) {
layer.close(i);
layer.close(index);// 關閉彈出層
$("#users")[0].reset()// 重置form
})
table.reload('testReload', {// 重載表格
page : {
curr : 1
// 重新從第 1 頁開始
}
})
} else {
layer.msg('添加失敗')
}
})
},
cancel : function(index, layero) {
$("#users")[0].reset()// 重置form
layer.close(index)
}
});
}
}
$('.layui-form .layui-btn').on('click', function() {
var type = $(this).data('type');
active[type] ? active[type].call(this) : '';
});
// table菜單
table.on('tool(user)', function(obj) {
var data = obj.data;// 獲得當前行數據
var layEvent = obj.event; // 獲得 lay-event 對應的值(也可以是表頭的event參數對應的值)
var tr = obj.tr; // 獲得當前行 tr 的DOM對象
if (layEvent == 'edit') {// 編輯
layer.open({
type : 1,
title : '編輯角色',
maxmin : true,
shadeClose : true, // 點擊遮罩關閉層
area : [ '80%', '80%' ],
content : $('#box1'),
btn : [ '確定', '取消' ],
success : function(layero, index) {// 彈出後執行的函數
$('#part_names').val(data.part_name);
$('#description').val(data.description);
layui.form.render('select');
},
yes : function(index, layero) {// 確定回調函數
$.ajaxSettings.async = false;
$.post(path + '/sy/partAction_eidt.action', {
part_name : $('#part_names').val(),
description : $('#description').val(),
part_id : data.part_id
}, function(data) {
if (data > 0) {
layer.alert('編輯成功', {
icon : 1,
title : '提示'
}, function(i) {
layer.close(i);
layer.close(index);// 關閉彈出層
$("#users")[0].reset()// 重置form
})
table.reload('testReload', {// 重載表格
page : {
curr : 1 // 重新從第 1 頁開始
}
})
} else if (data == -2) {
layer.msg('角色名稱重複')
} else {
layer.msg('編輯失敗')
}
})
},
cancel : function(index, layero) {
$("#users")[0].reset()// 重置form
layer.close(index)
}
})
} else if (layEvent == 'begin') {// 啓用
layer.confirm('確定啓用嗎???', {
icon : 3,
title : '提示'
}, function(index) {
$.getJSON(path + '/sy/partAction_eidtStatu.action', {
part_id:data.part_id,
statu:1
}, function(data) {
layer.close(index);
table.reload('testReload', {
page : {
curr : 1
// 重新從第 1 頁開始
}
})
});
})
} else if (layEvent == 'end') {// end//禁用
layer.confirm('確定禁用嗎???', {
icon : 3,
title : '提示'
}, function(index) {
$.getJSON(path + '/sy/partAction_eidtStatu.action', {
part_id:data.part_id,
statu:0
}, function(data) {
layer.close(index);
table.reload('testReload', {
page : {
curr : 1 // 重新從第 1 頁開始
}
})
});
})
} else if (layEvent == 'del') {// 刪除
layer.confirm('確定刪除嗎???', {
icon : 3,
title : '提示'
}, function(index) {
$.getJSON(path + '/sy/partAction_remove.action', {
part_id : data.part_id
}, function(data) {
layer.close(index);
table.reload('testReload', {
page : {
curr : 1
// 重新從第 1 頁開始
}
})
});
})
} else if (layEvent == 'right') {// 角色權限
layer.open({
type : 1,
title : '角色權限',
maxmin : true,
shadeClose : true, // 點擊遮罩關閉層
area : [ '60%', '95%' ],
content : $('#box3'),
btn : [ '確定', '取消' ],
success : function(layero, index) {
$.getJSON(path + '/sy/permissionAction_getPartTree.action', {
part_id : data.part_id
}, function(data) {
zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, data);
setCheck();
$("#py").bind("change", setCheck);
$("#sy").bind("change", setCheck);
$("#pn").bind("change", setCheck);
$("#sn").bind("change", setCheck);
});
},
yes : function(index, layero) {
nodes = zTreeObj.getCheckedNodes(true);
var permissionIds = "";
for (var i = 0; i < nodes.length; i++) {
permissionIds += "," + nodes[i].id;
}
if(permissionIds.length > 0){
permissionIds = permissionIds.substring(1);
}
$.getJSON(path + '/sy/permissionAction_partPermissionBinding.action', {
part_id : data.part_id,
permissionIds:permissionIds
}, function(data) {
layer.close(index);
table.reload('testReload', {
page : {
curr : 1 // 重新從第 1 頁開始
}
})
});
}
});
}
});
});
var setting = {
check : {
enable : true
},
data : {
simpleData : {
enable : true
}
}
};
var code;
function setCheck() {
var zTree = $.fn.zTree.getZTreeObj("treeDemo"), py = $("#py").attr(
"checked") ? "p" : "", sy = $("#sy").attr("checked") ? "s" : "", pn = $(
"#pn").attr("checked") ? "p" : "", sn = $("#sn").attr("checked") ? "s"
: "", type = {
"Y" : py + sy,
"N" : pn + sn
};
zTree.setting.check.chkboxType = type;
}
數據管理和js
Clazz.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Struts 實現CURD</title>
<link rel="stylesheet" href="${pageContext.request.contextPath }/static/js/layui/css/layui.css"/>
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/layui/layui.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery-3.3.1.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/Clazz.js"></script>
</head>
<body class="child-body">
<!--隱藏域傳值 -->
<input type="hidden" id="path"
value="${pageContext.request.contextPath}">
<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='searchName' name="searchName"
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>
<!--根據table id 來展示表格數據 -->
<table class="layui-hide" id="strutsClassTable" 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" method="post" onsubmit="return false" id="myFrom">
<div class="layui-form-item">
<label class="layui-form-label"> 名字</label>
<div class="layui-input-block">
<input type="text" class="layui-input" id="cname" name=cname><br>
</div>
<label class="layui-form-label">信息</label>
<div class="layui-input-block">
<input type="text" class="layui-input" id="cteachar" name=cteachar><br>
</div>
<label class="layui-form-label">圖片</label>
<div class="layui-input-block">
<input type="text" class="layui-input" id="pic" name=pic><br>
</div>
</div>
</form>
</div>
</body>
</html>
Clazz.js
//執行渲染
layui.use(['table','layer','form'],function(){
//定義通用全局變量
var path=document.getElementById("path").value;
var table =layui.table;
var layer=layui.layer;
var form = layui.form;
var $ = layui.$;
//展示數據表格(數據表格初始化)
table.render({
elem:'#strutsClassTable'//表格id
,url:path+'/sy/strutsClassAction_query.action'//所對應調用的接口
,method:'post' //提交方式
,cols:[[
/*根據數據庫的表格所對應的名稱 */
{field:'cid',height:80, width:300, title: '編號'}
,{field:'cname', height:80,width:300, title: '名字'}
,{field:'cteachar',height:80, width:300, title: '信息'}
,{field:'pic',height:80, width:300, title: '圖片'}
,{field:'right',height:80, width:300, title: '操作', toolbar:'#lineBtns'}//操作欄
]]
,page:'true'//分頁
, id: 'testReload'
});
//查詢和新增事件觸發
var active = {
//查詢
reload: function () {
var cname = $('#searchName').val();//獲取查詢內容
// 執行重載
table.reload('testReload', {
page: {
curr: 1// 從第1頁開始展示查詢結果
},
where: {
key: 'cname',
cname: cname
}
});
},
add: function () { //添加
layer.open({//彈出框
type: 1,
title: '添加信息',
maxmin: true,
shadeClose: true, //點擊遮罩關閉層
area: ['60%', '55%'],
content: $('#box1'),
btn: ['確定', '取消'],
//當點擊確定觸發回掉
yes: function (index, layero) {//確定執行函數
//通過向後臺返回ajax請求來添加數據
$.post(path+"/sy/strutsClassAction_add.action", {
//攜帶參數
cname:$("#cname").val(),
cteachar:$("#cteachar").val(),
pic:$("#pic").val()
}, function (data) {
/*根據後臺返回的參數來進行判斷是否添加成功 */
if (data > 0) {
//彈出提示層
layer.alert('添加成功', {icon: 1, title: '提示'}, function (i) {
layer.close(i);
layer.close(index);//關閉彈出層
$("#myFrom")[0].reset()//重置form
})
//重載表格
table.reload('testReload', {
page: {
curr: 1// 重新從第 1 頁開始
}
})
} else{
//提示添加失敗
layer.msg('添加失敗')
}
})
}, cancel: function (index, layero) {//取消
//當點擊取消按鈕
$("#myFrom")[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 tr=obj.tr//活動當前行tr 的 DOM對象
var layEvent = obj.event; //獲取操作狀態 修改和刪除
if(layEvent === 'del'){ //刪除
layer.confirm('確定刪除嗎?',{title:'刪除'}, function(index){
//向服務端發送刪除指令og
$.post(path+'/sy/strutsClassAction_remove.action',{cid:data.cid}, function(ret){
layer.close(index);//關閉彈窗
table.reload('testReload', {//重載表格
page: {
curr: 1// 重新從第 1 頁開始
}
})
});
layer.close(index);
});
} else if(layEvent === 'edit'){ //編輯
layer.open({
type: 1,
title: '修改信息',
maxmin: true,
shadeClose: true, //點擊遮罩關閉層
area: ['60%', '55%'],
content: $('#box1'),
btn: ['確定', '取消']
,content:$('#box1') //彈窗id
,success:function(layero,index){
//數據綁定
$('#cname').val(data.cname);
$('#cteachar').val(data.cteachar);
$("#pic").val(data.pic);
},yes:function(index,layero){
//確定修改回掉
$.post(path+'/sy/strutsClassAction_eidt.action',{
//攜帶參數
cname:$("#cname").val(),
cteachar:$("#cteachar").val(),
pic:$("#pic").val(),
cid:data.cid
},function(data){
//根據後臺返回的參數,來進行判斷
if(data>0){
layer.alert('編輯成功',{icon:1,title:'提示'},function(i){
layer.close(i);
layer.close(index);//關閉彈出層
$("#myFrom")[0].reset()//重置form
})
table.reload('testReload',{//重載表格
page:{
curr:1
}
})
}
});
}
});
}
});
});
後臺代碼
在這裏我就沒有展示實體類了,
dao
普通數據dao
package com.crud.dao;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import com.crud.entity.Clazz;
import com.crud.util.BaseDao;
import com.crud.util.JsonBaseDao;
import com.crud.util.JsonUtils;
import com.crud.util.PageBean;
import com.crud.util.StringUtils;
/**
* 普通數據
* @author Administrator
*
*/
public class dao extends JsonBaseDao {
/**
*查詢
* @param paMap
* @param pageBean
* @return
* @throws Exception
*/
public List<Map<String, Object>> query(Map<String, String[]> paMap, PageBean pageBean) throws Exception {
String sql = "select * from t_clazz where true ";
String cname = JsonUtils.getParamVal(paMap, "cname");
// 是否帶名稱查詢
if (StringUtils.isNotBlank(cname)) {
sql = sql + " and cname like '%" + cname + "%'";
}
String cid = JsonUtils.getParamVal(paMap, "cid");
// 帶id查詢
if (StringUtils.isNotBlank(cid)) {
sql = sql + " and cid = " + cid ;
}
return super.executeQuery(sql, pageBean);
}
/**
*修改
*
* @param paMap
* @return
* @throws Exception
*/
public int eidt(Map<String, String[]> paMap) throws Exception {
String sql = "update t_clazz set cname = ?, cteachar = ?, pic = ? where cid = ?";
return super.executeUpdate(sql, new String[] {"cname", "cteachar", "pic", "cid"}, paMap);
}
/**
*刪除
* @param paMap
* @return
* @throws Exception
*/
public int remove(Map<String, String[]> paMap) throws Exception {
// 刪除sql
String sql = "delete from t_clazz where cid = ?";
return super.executeUpdate(sql, new String[] { "cid" }, paMap);
}
/**
* 添加
*
* @param paMap
* @return
* @throws Exception
*/
public int add(Map<String, String[]> paMap) throws Exception {
String sql = "insert into t_clazz (cname, cteachar, pic)values (?,?,?)";
return super.executeUpdate(sql, new String[] { "cname", "cteachar", "pic"}, paMap);
}
}
用戶dao方法 userdao
package com.crud.dao;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import com.crud.entity.Clazz;
import com.crud.util.BaseDao;
import com.crud.util.JsonBaseDao;
import com.crud.util.JsonUtils;
import com.crud.util.PageBean;
import com.crud.util.StringUtils;
/**
* 普通數據
* @author Administrator
*
*/
public class dao extends JsonBaseDao {
/**
*查詢
* @param paMap
* @param pageBean
* @return
* @throws Exception
*/
public List<Map<String, Object>> query(Map<String, String[]> paMap, PageBean pageBean) throws Exception {
String sql = "select * from t_clazz where true ";
String cname = JsonUtils.getParamVal(paMap, "cname");
// 是否帶名稱查詢
if (StringUtils.isNotBlank(cname)) {
sql = sql + " and cname like '%" + cname + "%'";
}
String cid = JsonUtils.getParamVal(paMap, "cid");
// 帶id查詢
if (StringUtils.isNotBlank(cid)) {
sql = sql + " and cid = " + cid ;
}
return super.executeQuery(sql, pageBean);
}
/**
*修改
*
* @param paMap
* @return
* @throws Exception
*/
public int eidt(Map<String, String[]> paMap) throws Exception {
String sql = "update t_clazz set cname = ?, cteachar = ?, pic = ? where cid = ?";
return super.executeUpdate(sql, new String[] {"cname", "cteachar", "pic", "cid"}, paMap);
}
/**
*刪除
* @param paMap
* @return
* @throws Exception
*/
public int remove(Map<String, String[]> paMap) throws Exception {
// 刪除sql
String sql = "delete from t_clazz where cid = ?";
return super.executeUpdate(sql, new String[] { "cid" }, paMap);
}
/**
* 添加
*
* @param paMap
* @return
* @throws Exception
*/
public int add(Map<String, String[]> paMap) throws Exception {
String sql = "insert into t_clazz (cname, cteachar, pic)values (?,?,?)";
return super.executeUpdate(sql, new String[] { "cname", "cteachar", "pic"}, paMap);
}
}
角色dao方法partdao
package com.crud.dao;
import java.util.List;
import java.util.Map;
import com.crud.util.JsonBaseDao;
import com.crud.util.JsonUtils;
import com.crud.util.PageBean;
import com.crud.util.StringUtils;
/**
* 角色
*
* @author 201900514
*
*/
public class PartDao extends JsonBaseDao {
/**
* 添加
*
* @param paramMap
* @return
* @throws Exception
*/
public int add(Map<String, String[]> paramMap) throws Exception {
String sql = "insert into part(part_name,description, statu) values (?, ?, 1)";
return super.executeUpdate(sql, new String[] { "part_name", "description" }, paramMap);
}
/**
* 移除
*
* @param paramMap
* @return
* @throws Exception
*/
public int remove(Map<String, String[]> paramMap) throws Exception {
//移除用戶角色的中間表
super.executeUpdate("delete from user_and_part where part_id =" + JsonUtils.getParamVal(paramMap, "part_id"));
//移除角色菜單的中間表
super.executeUpdate(
"delete from part_and_permission where part_id = " + JsonUtils.getParamVal(paramMap, "part_id"));
return super.executeUpdate("delete from part where part_id = ?", new String[] { "part_id" }, paramMap);
}
/**
* 修改
*
* @param paramMap
* @return
* @throws Exception
*/
public int eidt(Map<String, String[]> paramMap) throws Exception {
String sql = "update part set part_name = ?, description = ? where part_id = ?";
return super.executeUpdate(sql, new String[] { "part_name", "description", "part_id" }, paramMap);
}
/**
* 修改狀態
*
* @param paramMap
* @return
* @throws Exception
*/
public int eidtStatu(Map<String, String[]> paramMap) throws Exception {
String sql = "update part set statu = ? where part_id = ?";
return super.executeUpdate(sql, new String[] { "statu", "part_id" }, paramMap);
}
/**
* 角色名是否存在
*
* @return
*/
public boolean isName(Map<String, String[]> paramMap) throws Exception {
List<Map<String, Object>> list = null;
if(StringUtils.isNotBlank(JsonUtils.getParamVal(paramMap, "part_id"))) {
String sql = "select part_id from part where part_id != ? and part_name = ?";
list = super.executeQuery(sql, new String[] { "part_id", "part_name" }, paramMap, null);
}else {
String sql = "select part_id from part where part_name = ?";
list = super.executeQuery(sql, new String[] {"part_name" }, paramMap, null);
}
return list != null && list.size() > 0;
}
/**
* 查詢
*
* @param paramMap
* @param pageBean
* @return
* @throws Exception
*/
public List<Map<String, Object>> query(Map<String, String[]> paramMap, PageBean pageBean) throws Exception {
String sql = "select part_id, part_name, description, statu from part where true ";
//模糊查
String part_name = JsonUtils.getParamVal(paramMap, "part_name");
if (StringUtils.isNotBlank(part_name)) {
sql += " and part_name like '%" + part_name + "%' ";
}
// ID查
String part_id = JsonUtils.getParamVal(paramMap, "part_id");
if (StringUtils.isNotBlank(part_id)) {
sql += " and user_id = " + part_id;
}
return super.executeQuery(sql, pageBean);
}
/**
*獲取角色下拉 只有可用的返回
* @return
* @throws Exception
*/
public List<Map<String, Object>> select() throws Exception {
String sql = "select part_id, part_name from part where statu = 1";
return super.executeQuery(sql, null);
}
}
菜單dao方法 permissiondao
package com.crud.dao;
import java.util.List;
import java.util.Map;
import com.crud.util.JsonBaseDao;
import com.crud.util.JsonUtils;
import com.crud.util.PageBean;
import com.crud.util.StringUtils;
/**
* 角色
*
* @author 20190313
*
*/
public class PartDao extends JsonBaseDao {
/**
* 添加
*
* @param paramMap
* @return
* @throws Exception
*/
public int add(Map<String, String[]> paramMap) throws Exception {
String sql = "insert into part(part_name,description, statu) values (?, ?, 1)";
return super.executeUpdate(sql, new String[] { "part_name", "description" }, paramMap);
}
/**
* 移除
*
* @param paramMap
* @return
* @throws Exception
*/
public int remove(Map<String, String[]> paramMap) throws Exception {
//移除用戶角色的中間表
super.executeUpdate("delete from user_and_part where part_id =" + JsonUtils.getParamVal(paramMap, "part_id"));
//移除角色菜單的中間表
super.executeUpdate(
"delete from part_and_permission where part_id = " + JsonUtils.getParamVal(paramMap, "part_id"));
return super.executeUpdate("delete from part where part_id = ?", new String[] { "part_id" }, paramMap);
}
/**
* 修改
*
* @param paramMap
* @return
* @throws Exception
*/
public int eidt(Map<String, String[]> paramMap) throws Exception {
String sql = "update part set part_name = ?, description = ? where part_id = ?";
return super.executeUpdate(sql, new String[] { "part_name", "description", "part_id" }, paramMap);
}
/**
* 修改狀態
*
* @param paramMap
* @return
* @throws Exception
*/
public int eidtStatu(Map<String, String[]> paramMap) throws Exception {
String sql = "update part set statu = ? where part_id = ?";
return super.executeUpdate(sql, new String[] { "statu", "part_id" }, paramMap);
}
/**
* 角色名是否存在
*
* @return
*/
public boolean isName(Map<String, String[]> paramMap) throws Exception {
List<Map<String, Object>> list = null;
if(StringUtils.isNotBlank(JsonUtils.getParamVal(paramMap, "part_id"))) {
String sql = "select part_id from part where part_id != ? and part_name = ?";
list = super.executeQuery(sql, new String[] { "part_id", "part_name" }, paramMap, null);
}else {
String sql = "select part_id from part where part_name = ?";
list = super.executeQuery(sql, new String[] {"part_name" }, paramMap, null);
}
return list != null && list.size() > 0;
}
/**
* 查詢
*
* @param paramMap
* @param pageBean
* @return
* @throws Exception
*/
public List<Map<String, Object>> query(Map<String, String[]> paramMap, PageBean pageBean) throws Exception {
String sql = "select part_id, part_name, description, statu from part where true ";
//模糊查
String part_name = JsonUtils.getParamVal(paramMap, "part_name");
if (StringUtils.isNotBlank(part_name)) {
sql += " and part_name like '%" + part_name + "%' ";
}
// ID查
String part_id = JsonUtils.getParamVal(paramMap, "part_id");
if (StringUtils.isNotBlank(part_id)) {
sql += " and user_id = " + part_id;
}
return super.executeQuery(sql, pageBean);
}
/**
*獲取角色下拉 只有可用的返回
* @return
* @throws Exception
*/
public List<Map<String, Object>> select() throws Exception {
String sql = "select part_id, part_name from part where statu = 1";
return super.executeQuery(sql, null);
}
}
util
這是util包裏的類
basetdao
package com.crud.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
* 閫氱敤鐨勬煡璇㈡柟娉� 23縐嶈璁℃ā寮忎箣絳栫暐妯″紡 浣滅敤錛氬湪鏂規硶鎴栫被涓凡緇忓畬鎴愪簡瀵瑰簲鐨勫姛鑳斤紝鐒跺悗鍦ㄨ皟鐢ㄦ柟鍘繪牴鎹嚜宸辯殑闇�奼傚幓澶勭悊緇撴灉銆� 浣垮緱浠g爜鏇村姞鐏墊椿銆�
*
* @author Administrator
*
* @param <T>
*/
public class BaseDao<T> {
// $.ajax
protected interface Callback<T> {
public List<T> foreach(ResultSet rs) throws SQLException, InstantiationException, IllegalAccessException;
}
public List<T> executeQuery(String sql, PageBean pageBean, Callback<T> callback)
throws SQLException, InstantiationException, IllegalAccessException {
if (pageBean != null && pageBean.isPagination()) {
Connection con = DBAccess.getConnection();
String countSql = getCountSql(sql);
PreparedStatement countPst = con.prepareStatement(countSql);
ResultSet countRs = countPst.executeQuery();
if (countRs.next()) {
pageBean.setTotal(countRs.getObject(1).toString());
}
DBAccess.close(null, countPst, countRs);
String pageSql = getPageSql(sql, pageBean);
PreparedStatement pagePst = con.prepareStatement(pageSql);
ResultSet pageRs = pagePst.executeQuery();
try {
return callback.foreach(pageRs);
} finally {
DBAccess.close(con);
}
} else {
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
try {
return callback.foreach(rs);
} finally {
DBAccess.close(con);
}
}
}
/**
* 鍙敤浣跨敤鏁扮粍榪涜璧嬪��
* @param sql
* @param pageBean
* @param callback
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public List<T> executeQueryToarray(String sql,String[] attrs, Map<String, String[]> paMap, PageBean pageBean, Callback<T> callback)
throws SQLException, InstantiationException, IllegalAccessException {
if (pageBean != null && pageBean.isPagination()) {
Connection con = DBAccess.getConnection();
String countSql = getCountSql(sql);
PreparedStatement countPst = con.prepareStatement(countSql);
for (int i = 0; i < attrs.length; i++) {
countPst.setObject(i + 1, JsonUtils.getParamVal(paMap, attrs[i]));
}
ResultSet countRs = countPst.executeQuery();
if (countRs.next()) {
pageBean.setTotal(countRs.getObject(1).toString());
}
DBAccess.close(null, countPst, countRs);
String pageSql = getPageSql(sql, pageBean);
PreparedStatement pagePst = con.prepareStatement(pageSql);
for (int i = 0; i < attrs.length; i++) {
pagePst.setObject(i + 1, JsonUtils.getParamVal(paMap, attrs[i]));
}
ResultSet pageRs = pagePst.executeQuery();
try {
return callback.foreach(pageRs);
} finally {
DBAccess.close(con);
}
} else {
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
for (int i = 0; i < attrs.length; i++) {
pst.setObject(i + 1, JsonUtils.getParamVal(paMap, attrs[i]));
}
ResultSet rs = pst.executeQuery();
try {
return callback.foreach(rs);
} finally {
DBAccess.close(con);
}
}
}
/**
* 灝嗗師鐢熸�佺殑sql璇彞杞崲鎴愭煡瀵瑰簲鐨勫綋欏佃褰曟暟sql璇彞
*
* @param sql
* @param pageBean
* @return
*/
private String getPageSql(String sql, PageBean pageBean) {
return sql + " limit " + pageBean.getStartIndex() + "," + pageBean.getRows();
}
/**
* 灝嗗師鐢熸�佺殑sql璇彞杞崲鎴愭煡鎬昏褰曡緭鐨剆ql璇彞
*
* @param sql
* @return
*/
private String getCountSql(String sql) {
return "select count(1) from (" + sql + " ) t";
}
}
jsonbasedao
package com.cpc.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class JsonBaseDao extends BaseDao<Map<String, Object>> {
public List<Map<String, Object>> executeQuery(String sql, PageBean pageBean)
throws SQLException, InstantiationException, IllegalAccessException {
return super.executeQuery(sql, pageBean, new Callback<Map<String, Object>>() {
@Override
public List<Map<String, Object>> foreach(ResultSet rs)
throws SQLException, InstantiationException, IllegalAccessException {
/*
* 1銆佸壋寤轟竴涓疄浣撶被鐨勫疄渚� 2銆佺粰鍒涘緩鐨勫疄渚嬪睘鎬ц祴鍊� 3銆佸皢娣誨姞瀹岀被瀹圭殑瀹炰綋綾繪坊鍔犲埌list闆嗗悎涓�
*/
// list.add(new Book(rs.getInt("bid"), rs.getString("bname"),
// rs.getFloat("price")));
List<Map<String, Object>> list = new ArrayList<>();
// 鑾峯彇婧愭暟鎹�
ResultSetMetaData md = rs.getMetaData();
int count = md.getColumnCount();
Map<String, Object> map = null;
while (rs.next()) {
map = new HashMap<>();
for (int i = 1; i <= count; i++) {
map.put(md.getColumnName(i), rs.getObject(i));
}
list.add(map);
}
return list;
}
});
}
public List<Map<String, Object>> executeQuery(String sql, String[] attrs, Map<String, String[]> paMap,
PageBean pageBean) throws Exception {
return super.executeQueryToarray(sql, attrs, paMap, pageBean, new Callback<Map<String, Object>>() {
@Override
public List<Map<String, Object>> foreach(ResultSet rs)
throws SQLException, InstantiationException, IllegalAccessException {
/*
* 1銆佸壋寤轟竴涓疄浣撶被鐨勫疄渚� 2銆佺粰鍒涘緩鐨勫疄渚嬪睘鎬ц祴鍊� 3銆佸皢娣誨姞瀹岀被瀹圭殑瀹炰綋綾繪坊鍔犲埌list闆嗗悎涓�
*/
// list.add(new Book(rs.getInt("bid"), rs.getString("bname"),
// rs.getFloat("price")));
List<Map<String, Object>> list = new ArrayList<>();
// 鑾峯彇婧愭暟鎹�
ResultSetMetaData md = rs.getMetaData();
int count = md.getColumnCount();
Map<String, Object> map = null;
while (rs.next()) {
map = new HashMap<>();
for (int i = 1; i <= count; i++) {
map.put(md.getColumnName(i), rs.getObject(i));
}
list.add(map);
}
return list;
}
});
}
/**
* 根據sql語句查詢,查出第一位
* 數據庫中只返回一位
* @param sql
* @return
* @throws Exception
*/
public Object executeByObject(String sql) throws Exception {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
Object o = 0;
try {
con = DBAccess.getConnection();
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
if(rs.next()) {
o = rs.getObject(1);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
DBAccess.close(con, pst, rs);
}
return o;
}
/**
* 根據sql語句查詢,查第一位(只返回一條),並且返回類型是Integer的
* @param sql
* @return
* @throws Exception
*/
public Integer executeByInteger(String sql) throws Exception {
return Integer.parseInt(executeByObject(sql).toString());
}
/**
* 根據sql語句查詢,查出Set<Integer>
* 注意:第一位必須是int類型(數據庫中)
* @param sql
* @return
* @throws Exception
*/
public Set<Integer> executeByIntegers(String sql) throws Exception {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
Set<Integer> set = new HashSet<Integer>();
try {
con = DBAccess.getConnection();
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()) {
set.add(rs.getInt(1));
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
DBAccess.close(con, pst, rs);
}
return set;
}
/**
*
* @param sql
* @param attrs
* map涓殑key
* @param paMap
* jsp鍚戝悗鍙頒紶閫掔殑鍙傛暟闆嗗悎
* @return
* @throws SQLException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public int executeUpdate(String sql, String[] attrs, Map<String, String[]> paramMap) throws SQLException,
NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Connection con = null;
PreparedStatement pst = null;
int n = 0;
try {
con = DBAccess.getConnection();
pst = con.prepareStatement(sql);
for (int i = 0; i < attrs.length; i++) {
pst.setObject(i + 1, JsonUtils.getParamVal(paramMap, attrs[i]));
}
n = pst.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
DBAccess.close(con, pst, null);
}
return n;
}
/**
* 閫氱敤澧炲垹鏀�
*
* @param sql
* @return
* @throws Exception
*/
public int executeUpdate(String sql){
Connection con = null;
PreparedStatement pst = null;
int n = 0;
try {
con = DBAccess.getConnection();
pst = con.prepareStatement(sql);
n = pst.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
} finally {
DBAccess.close(con, pst, null);
}
return n;
}
}
responseutil
package com.crud.util;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import cn.hutool.json.JSONUtil;
public class ResponseUtil {
/**
* 閫氱敤鐨勫疄鐜�
*
* @param response
* @param o
* @throws Exception
*/
public static void write(HttpServletResponse response, Object o) throws Exception {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println(o.toString());
out.flush();
out.close();
}
/**
* 轉json格式輸出到頁面
* @param response
* @param o
* @throws Exception
*/
public static void writeJSON(HttpServletResponse response, Object o) throws Exception {
write(response, JSON.toJSONString(o));
}
}
web
useraction
package com.crud.web;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.crud.dao.UserDao;
import com.crud.entity.User;
import com.crud.util.PageBean;
import com.crud.util.ResponseUtil;
/**
* 用戶請求啊action
*
* @author 20190313
*
*/
public class UserAction extends BaseAction {
private UserDao userDao = new UserDao();
/**
* 查詢
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String query() throws Exception {
PageBean pageBean = new PageBean();
pageBean.setPageBean(request);
List<Map<String, Object>> list = userDao.query(request.getParameterMap(), pageBean);
Map<String, Object> map = new HashMap<>();
map.put("code", 0);
map.put("count", pageBean.getTotal());
map.put("data", list);
// 以json格式返回
ResponseUtil.writeJSON(response, map);
return null;
}
/**
* 刪除
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String remove() throws Exception {
// 以json格式輸出
ResponseUtil.writeJSON(response, userDao.remove(request.getParameterMap()));
return null;
}
/**
* 登錄 1登錄成功,-1登錄失敗
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String login() throws Exception {
User user = userDao.login(request.getParameterMap());
// 判斷
if (user != null) {
//將user對象放入sesion中
request.getSession().setAttribute("user", user);
ResponseUtil.writeJSON(response, 1);
return null;
}
ResponseUtil.writeJSON(response, -1);
return null;
}
/**
* 增加
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String add() throws Exception {
// 判斷用戶名是重複
if (userDao.isName(request.getParameterMap())) {
// 用戶名重複返回-2
ResponseUtil.writeJSON(response, -2);
return null;
}
// 以json格式返回
ResponseUtil.writeJSON(response, userDao.add(request.getParameterMap()));
return null;
}
/**
* 修改
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String edit() throws Exception {
// 判斷用戶名是重複
if (userDao.isName(request.getParameterMap())) {
// 用戶名重複返回-2
ResponseUtil.writeJSON(response, -2);
return null;
}
ResponseUtil.writeJSON(response, userDao.edit(request.getParameterMap()));
return null;
}
/**
* ̬修改用戶狀態
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String eidtStatu() throws Exception {
ResponseUtil.writeJSON(response, userDao.eidtStatu(request.getParameterMap()));
return null;
}
/**
*用戶退出登錄
* @return
* @throws Exception
*/
public String exit() throws Exception {
//退出登錄
request.getSession().removeAttribute("user");
ResponseUtil.writeJSON(response, 1);
return null;
}
}
Clazzaction
package com.crud.web;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.crud.dao.dao;
import com.crud.util.BaseAction;
import com.crud.util.PageBean;
import com.crud.util.ResponseUtil;
public class ClazzAction extends BaseAction{
private dao clzDao = new dao();
/**
* 添加
* @return
* @throws Exception
*/
public String add() throws Exception {
int n = clzDao.add(request.getParameterMap());
ResponseUtil.writeJSON(response, n);
return null;
}
/**
* 查詢
* @return
* @throws Exception
*/
public String query() throws Exception {
PageBean pageBean = new PageBean();
List<Map<String, Object>> list = clzDao.query(request.getParameterMap(), pageBean);
Map<String, Object> map = new HashMap<String, Object>();
map.put("code", 0);
map.put("count", pageBean.getTotal());
map.put("data", list);
//以JSON格式返回
ResponseUtil.writeJSON(response, map);
return null;
}
/**
*修改
* @return
* @throws Exception
*/
public String eidt() throws Exception {
int n = clzDao.eidt(request.getParameterMap());
ResponseUtil.writeJSON(response, n);
return null;
}
/**
* 刪除
* @return
* @throws Exception
*/
public String remove() throws Exception {
int n = clzDao.remove(request.getParameterMap());
ResponseUtil.write(response, n);
return null;
}
}
partaction
package com.crud.web;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.crud.dao.PartDao;
import com.crud.util.PageBean;
import com.crud.util.ResponseUtil;
public class PartAction extends BaseAction {
private PartDao partDao = new PartDao();
/**
* 查詢
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String query() throws Exception {
PageBean pageBean = new PageBean();
pageBean.setPageBean(request);
List<Map<String, Object>> list = partDao.query(request.getParameterMap(), pageBean);
Map<String, Object> map = new HashMap<>();
//要與layui的格式保持一致
map.put("code", 0);
map.put("count", pageBean.getTotal());
map.put("data", list);
// json
ResponseUtil.writeJSON(response, map);
return null;
}
/**
* 獲取角色下拉 只有可用的返回
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String select() throws Exception {
// json
ResponseUtil.writeJSON(response, partDao.select());
return null;
}
/**
* 刪除
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String remove() throws Exception {
// json
ResponseUtil.writeJSON(response, partDao.remove(request.getParameterMap()));
return null;
}
/**
* 添加
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String add() throws Exception {
// 判斷角色名是重複
if (partDao.isName(request.getParameterMap())) {
// 返回-1
ResponseUtil.writeJSON(response, -1);
return null;
}
//json
ResponseUtil.writeJSON(response, partDao.add(request.getParameterMap()));
return null;
}
/**
*修改
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String eidt() throws Exception {
// 判斷角色名是重複
if (partDao.isName(request.getParameterMap())) {
// 返回-2
ResponseUtil.writeJSON(response, -2);
return null;
}
// json
ResponseUtil.writeJSON(response, partDao.eidt(request.getParameterMap()));
return null;
}
/**
* 修改角色狀態״̬
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String eidtStatu() throws Exception {
// json
ResponseUtil.writeJSON(response, partDao.eidtStatu(request.getParameterMap()));
return null;
}
}
permissionaction
package com.crud.web;
import java.sql.SQLException;
import com.crud.dao.PermissionDao;
import com.crud.util.ResponseUtil;
/**
* 權限請求Action
* @author 20190313
*
*/
public class PermissionAction extends BaseAction{
PermissionDao permissionDao = new PermissionDao();
/**
* 獲取角色權限賦值tree
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String getPartTree() throws Exception {
// 以json格式返回
ResponseUtil.writeJSON(response, permissionDao.getPartTree(request.getParameterMap()));
return null;
}
/**
*角色授權
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String partPermissionBinding() throws Exception {
permissionDao.partPermissionBinding(request.getParameterMap());
ResponseUtil.writeJSON(response, 1);
return null;
}
/**
*獲取用戶權限菜單,根據用戶ID
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String getUserTree() throws Exception {
ResponseUtil.writeJSON(response, permissionDao.getUserTree(request.getParameterMap()));
return null;
}
}
效果展示
登錄界面
主界面
角色管理
用戶管理
普通數據管理(測試用)