一、角色分页操作
(1) 思路
(2) 代码 — 后端
① 创建数据库表
CREATE TABLE `project_crowd`.`t_role` ( `id` INT NOT NULL, `name` CHAR(100), PRIMARY KEY(`id`) );
ALTER TABLE `project_crowd`.`t_role` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT;
② 逆向生成资源
将生成的资源各归其位,和之前admin的一样
③ SQL语句
<select id="selectRoleByKeyword" resultMap="BaseResultMap">
select id, name from t_role
where name like concat("%",#{keyword},"%")
</select>
④ RoleMapper 接口
List<Role> selectRoleByKeyword(String keyword);
⑤ RoleService 接口和实现
// 获取角色分页信息
PageInfo<Role> getPageInfo(int pageNum,int pageSize,String keyword);
@Override
public PageInfo<Role> getPageInfo(int pageNum, int pageSize, String keyword) {
// 开启分页功能
PageHelper.startPage(pageNum,pageSize);
// 执行查询
List<Role> roleList = roleMapper.selectRoleByKeyword(keyword);
// 封装为PageInfo对象并返回
return new PageInfo<>(roleList);
}
⑥ RoleHandler
@RequestMapping("/role/get/page/info.json")
public ResultEntity<PageInfo<Role>> getPageInfo(
@RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
@RequestParam(value = "pageSize",defaultValue = "5") int pageSize,
@RequestParam(value = "keyword",defaultValue = "") String keyword
) {
// 调取service方法获取分页数据
PageInfo<Role> pageInfo = roleService.getPageInfo(pageNum, pageSize, keyword);
// 封装到 ResultEntity 对象中返回(如果上面的操作抛出异常,交给异常映射机制处理)
return ResultEntity.successWithData(pageInfo);
}
(3) 代码:过渡
① 配置 view-controller
<!-- 角色分页界面-->
<mvc:view-controller path="/role/to/page.html" view-name="role-page" />
② 完善 role-page.jsp
③ 修改“角色维护”超链接
<li style="height:30px;">
<a href="role/to/page.html"><i class="glyphicon glyphicon-king"></i> 角色维护</a>
</li>
(4) 代码 — 前端
① 初始化数据
$(function(){
// 1.为分页操作准备初始化数据
window.pageNum = 1;
window.pageSize = 5;
window.keyword = "";
// 2.调用执行分页的函数,显示分页效果
generatePage();
});
② 创建外部 JavaScript 文件
在 role-page.jsp 引入外部 JavaScript 文件 my-role.js
<script type="text/javascript" src="crowd/my-role.js"></script>
③ 在 role-page.jsp 中引入 Pagination 环境
在 my-role 前面
<link rel="stylesheet" href="css/pagination.css">
<script type="text/javascript" src="jquery/jquery.pagination.js"></script>
在role-page中需要添加的id为,js 中需要使用
<tbody id="rolePageBody"></tbody>
<div id="Pagination" class="pagination"><!-- 这里显示分页 --></div>
④ 外部函数一:generatePage()
// 执行分页,生成页面效果,任何时候调用这个函数都会重新加载页面
function generatePage() {
// 1.获取分页数据
var pageInfo = getPageInfoRemote();
// 2.填充表格
fillTableBody(pageInfo);
}
⑤ 外部函数二:getPageInfoRemote()
★ 出现的问题
// 远程访问服务器端程序获取pageInfo数据
function getPageInfoRemote() {
// 调用$.ajax()函数发送请求并接受$.ajax()函数的返回值
var ajaxResult = $.ajax({
"url": "role/get/page/info.json",
"type": "post",
"data": {
"pageNum": window.pageNum,
"pageSize": window.pageSize,
"keyword": window.keyword
},
"async": false,
"dataType": "json"
});
console.log(ajaxResult);
// 判断当前响应状态码是否为200
var statusCode = ajaxResult.status;
// 如果当前响应状态码不是200,说明发生了错误或其他意外情况,显示提示消息,让当前函数停止执行
if(statusCode != 200) {
layer.msg("失败!响应状态码="+statusCode+" 说明信息="+ajaxResult.statusText);
return null;
}
// 如果响应状态码是200,说明请求处理成功,获取pageInfo
var resultEntity = ajaxResult.responseJSON;
// 从resultEntity中获取result属性
var result = resultEntity.result;
// 判断result是否成功
if(result == "FAILED") {
layer.msg(resultEntity.message);
return null;
}
// 确认result为成功后获取pageInfo
var pageInfo = resultEntity.queryData;
// 在控制台中打印日志,看看pageinfo是否有值
// 一开始一直没有值,经排查,将上面的resultEntity.data 改为 queryData
// 通过F12控制台的中ajaxResult的内容可以看到,没有data,数据都在queryData中
console.log("pageinfo= " + pageInfo);
// 返回pageInfo
return pageInfo;
}
⑥ 外部函数三:fillTableBody(pageInfo)
给 role-page.jsp 中的 tbody 标签加上 id=rolePageBody
// 填充表格
function fillTableBody(pageInfo) {
// 清除 tbody 中的旧的内容
$("#rolePageBody").empty();
// 这里清空是为了让没有搜索结果时不显示页码导航条
$("#Pagination").empty();
// 判断 pageInfo 对象是否有效
if (pageInfo == null || pageInfo == undefined || pageInfo.list == null || pageInfo.list.length == 0) {
$("#rolePageBody").append("<tr><td colspan='4' align='center'>抱歉!没有查询到您搜索的数据!</td></tr>");
return;
}
// 使用 pageInfo 的 list 属性填充 tbody
for (var i = 0; i < pageInfo.list.length; i++) {
var role = pageInfo.list[i];
var roleId = role.id;
var roleName = role.name;
var numberTd = "<td>" + (i + 1) + "</td>";
var checkboxTd = "<td><input type='checkbox'></td>";
var roleNameTd = "<td>" + roleName + "</td>";
var checkBtn = "<button type='button' class='btn btn-success btn-xs'><i class=' glyphicon glyphicon-check'></i></button>";
var pencilBtn = "<button type='button' class='btn btn-primary btn-xs'><i class=' glyphicon glyphicon-pencil'></i></button>";
var removeBtn = "<button type='button' class='btn btn-danger btn-xs'><i class=' glyphicon glyphicon-remove'></i></button>";
var buttonTd = "<td>" + checkBtn + " " + pencilBtn + " " + removeBtn + "</td>";
var tr = "<tr>" + numberTd + checkboxTd + roleNameTd + buttonTd + "</tr>";
$("#rolePageBody").append(tr);
}
// 生成分页导航条
generateNavigator(pageInfo);
}
⑦ 外部函数四:generateNavigator(pageInfo)
// 生成分页页码导航条
function generateNavigator(pageInfo) {
// 获取总记录数
var totalRecord = pageInfo.total;
// 声明相关属性
var properties = { "num_edge_entries": 3, "num_display_entries": 5, "callback": paginationCallBack, "items_per_page": pageInfo.pageSize, "current_page": pageInfo.pageNum - 1, "prev_text": "上一页", "next_text": "下一页"
}
// 调用 pagination()函数
$("#Pagination").pagination(totalRecord, properties);
}
⑧ 外部函数五:paginationCallBack(pageIndex, jQuery)
// 翻页时的回调函数
function paginationCallBack(pageIndex, jQuery) {
// 修改 window 对象的 pageNum 属性
window.pageNum = pageIndex + 1;
// 调用分页函数
generatePage();
// 取消页码超链接的默认行为
return false;
}
二、关键词搜索
(1) 思路
(2) 代码
在 role-page 页面
// 3.给查询按钮绑定单击函数
$("#searchBtn").click(function () {
// 获取关键词数据并赋值给全部变量
window.keyword = $("#keywordInput").val();
// 调用执行分页的函数,显示分页效果
generatePage();
});
三、新增角色信息
(1) 思路
(2) 代码 — 前端
① 创建 JSP 文件
② 加入模态框的HTML代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<div id="addModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">尚筹网系统弹窗</h4>
</div>
<div class="modal-body">
<form class="form-signin" role="form">
<div class="form-group has-success has-feedback">
<input id="roleNameInput" type="text" name="roleName"
class="form-control" placeholder="请输入角色名称" autofocus>
</div>
</form>
</div>
<div class="modal-footer">
<button id="saveRoleBtn" type="button" class="btn btn-primary"> 保 存
</button>
</div>
</div>
</div>
</div>
</html>
③ 在 role-page.jsp 引入上面的文件
<%@include file="modal-role-add.jsp" %>
④ 修改新增按钮的id
<button type="button" id="showAddModalBtn" class="btn btn-primary" style="float:right;"><i class="glyphicon glyphicon-plus"></i> 新增</button>
⑤ 给新增按钮绑定单击响应函数
// 4.给新增按钮绑定单击响应函数
$("#showAddModalBtn").click(function () {
// 显示模态框
$("#addModal").modal("show");
});
⑥ 执行保存
★ 出现的问题
和前面类似,就是页面json数据的参数名写错了,找了半天错误,数据能添加到数据库,但是页面不会跳转,后来发现response似乎没有result这个参数,然后去在控制台打印ajax,发现存结果的参数叫operationResult,后来发现,在之前的js中类似的错误还不少,然后都改了一下,例如messege改为operationMessage等等。
// 5. 给新增模态框中的保存按钮绑定单击响应函数
$("#saveRoleBtn").click(function () {
// ①用户在文本框中输入的角色名称
// #addModal表示整个模态框
// 空格表示后代元素中继续查找
// [name=roleName]表示匹配name属性基于roleName的元素
var roleNameInput = $.trim($("#roleNameInput").val());
// console.log(roleName);
// ②发送ajax请求
$.ajax({
"url": "role/add.json",
"type": "post",
"data": {
"name": roleNameInput
},
"dataType": "json",
"success": function (response) {
// 把result改为operationResult才有效
var result = response.operationResult;
if(result == "SUCCESS"){
layer.msg("操作成功!");
// 重新加载分页
// 将页码定位到最后一页
window.pageNum = 999999;
generatePage();
}
if(result == "FAILED"){
layer.msg("操作失败!" + response.message);
}
},
"error": function (response) {
layer.msg(response.status + " " + response.status.statusText);
}
});
// 关闭模态框
$("#addModal").modal("hide");
// 清理模态框
$("#roleNameInput").val("");
});
(3) 代码 ---- 后端
① roleHandler
// 角色保存
@ResponseBody
@RequestMapping("/role/add.json")
public ResultEntity<String> roleAdd(Role role) {
// 执行添加角色
roleService.addRole(role);
return ResultEntity.successWithoutData();
}
② RoleService
// 添加角色
void addRole(Role role);
③ RoleServiceImpl
// 添加角色
@Override
public void addRole(Role role) {
roleMapper.insert(role);
}
四、更新角色信息
(1) 思路
(2) 页面引入模态框
① 创建 JSP 文件
② 加入模态框的 HTML 代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<div id="editModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">尚筹网系统弹窗</h4>
</div>
<div class="modal-body">
<form class="form-signin" role="form">
<div class="form-group has-success has-feedback">
<input id="roleNameInputForUpdate" type="text" name="roleName"
class="form-control" placeholder="请输入角色名称" autofocus>
</div>
</form>
</div>
<div class="modal-footer">
<button id="updateRoleBtn" type="button" class="btn btn-primary"> 更 新
</button>
</div>
</div>
</div>
</div>
</html>
③ 在 role-page.jsp 引入
<%@include file="modal-role-edit.jsp" %>
(3) 打开模态框(回显)
① 修改“铅笔”按钮
修改 fillTableBody()函数
// 通过button标签的id属性(别的属性其实也可以)把roleId值传递到button按钮的单击响应函数中,在单击响应函数中使用this.id
var pencilBtn = "<button id='"+roleId+"' type='button' class='btn btn-primary btn-xs pencilBtn'><iclass=' glyphicon glyphicon-pencil'></i></button>";
② 给“铅笔”按钮绑定单击响应函数
// 6.给页面上的“铅笔”按钮绑定单击响应函数,目的是打开模态框
// 传统的事件绑定方式只能在第一个页面有效,翻页后失效了
// $(".pencilBtn").click(function(){
// alert("aaaa...");
// });
// 使用 jQuery 对象的 on()函数可以解决上面问题
// ①首先找到所有“动态生成”的元素所附着的“静态”元素
// ②on()函数的第一个参数是事件类型
// ③on()函数的第二个参数是找到真正要绑定事件的元素的选择器
// ③on()函数的第三个参数是事件的响应函数
$("#rolePageBody").on("click",".pencilBtn",function () {
// 打开模态框
$("#editModal").modal("show");
// 获取表格中当前行中的角色名称
var roleName = $(this).parent().prev().text();
// 获取当前角色的 id
// 依据是:var pencilBtn = "<button id='"+roleId+"' ……这段代码中我们把 roleId 设置到id 属性了
// 为了让执行更新的按钮能够获取到 roleId 的值,把它放在全局变量上
window.roleId = this.id;
// 使用 roleName 的值设置模态框中的文本框
$("#roleNameInputForUpdate").val(roleName);
});
(4) 代码:执行更新 — 前端
// 7.给更新模态框中的更新按钮绑定单击响应函数
$("#updateRoleBtn").click(function () {
// ①从文本框中获取新的角色名称
var roleNameInputForUpdate = $("#roleNameInputForUpdate").val();
// ②发送 Ajax 请求执行更新
$.ajax({
"url":"role/update.json",
"type":"post",
"data":{
"id":window.roleId,
"name":roleNameInputForUpdate
},
"dataType":"json",
"success":function(response){
var result = response.operationResult;
if(result == "SUCCESS") {
layer.msg("操作成功!");
// 重新加载分页数据
generatePage();
}
if(result == "FAILED") {
layer.msg("操作失败!"+response.message);
}
},
"error":function(response){
layer.msg(response.status+" "+response.statusText);
}
});
// 结束操作后,隐藏模态框
$("#editModal").modal("hide");
});
(5) 代码:执行更新 — 后端
① RoleHandler
// 角色修改
@ResponseBody
@RequestMapping("/role/update.json")
public ResultEntity<String> roleUpdate(Role role) {
// 执行修改角色
roleService.updateRole(role);
return ResultEntity.successWithoutData();
}
② RoleService
void updateRole(Role role);
③ RoleServiceImpl
// 修改角色
@Override
public void updateRole(Role role) {
roleMapper.updateByPrimaryKey(role);
}
五、删除角色信息
(1) 思路
(2) 代码 执行删除 — 后端
① RoleHandler
// 角色删除
@ResponseBody
@RequestMapping("/role/delete/by/role/id/array.json")
public ResultEntity<String> deleteByRoleIdArray(@RequestBody List<Integer> roleIdList) {
// 执行删除
roleService.deleteRole(roleIdList);
return ResultEntity.successWithoutData();
}
② RoleService
void deleteRole(List<Integer> roleIdList);
③ RoleServiceImpl
// 删除角色
@Override
public void deleteRole(List<Integer> roleIdList) {
RoleExample example = new RoleExample();
Criteria criteria = example.createCriteria();
// delete from t_role where id in (5,8,12)
criteria.andIdIn(roleIdList);
roleMapper.deleteByExample(example);
}
(3) 代码 执行删除 — 前端
① 新建 jsp 文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<div id="confirmModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">尚筹网系统弹窗</h4>
</div>
<div class="modal-body">
<h4>请确认是否要删除以下角色</h4>
<div id="roleNameDiv" style="text-align: center"></div>
</div>
<div class="modal-footer">
<button id="removeRoleBtn" type="button" class="btn btn-primary"> 确认删除
</button>
</div>
</div>
</div>
</div>
</html>
② 外部函数 showConfirmModal() 函数
// 声明专门函数显示确认模态框
function showConfirmModal(roleArray) {
// 打开模态框
$("#confirmModal").modal("show");
// 清除旧的数据
$("#roleNameDiv").empty();
// 在全局变量范围内创建数组来存放角色id
window.roleIdArray = [];
// 遍历这个数组
for(var i = 0; i < roleArray.length; i++){
var role = roleArray[i];
var roleName = role.roleName;
$("#roleNameDiv").append(roleName+"<br/>");
var roleId = role.roleId;
// 调用数组对象的push()方法存入新元素
window.roleIdArray.push(roleId);
}
}
③ 在 role-page.jsp 中引入
<%@include file="modal-role-confirm.jsp" %>
④ 为模态框中的 “确认删除” 按钮绑定单击事件
(以下操作需要修改或添加一些 id值)
// 8.点击确认模态框中的确认删除按钮进行角色的删除
$("#removeRoleBtn").click(function () {
// 从全局变量范围内获取roleIdArray,转换为JSON字符串
var requestBody = JSON.stringify(window.roleIdArray);
$.ajax({
url: "role/delete/by/role/id/array.json",
type: "post",
data: requestBody,
contentType: "application/json; charset=UTF-8",
dataType: "json",
success: function (response) {
var result = response.operationResult;
if(result == "SUCCESS"){
layer.msg("操作成功!");
// 重新加载分页
generatePage();
}
if(result == "FAILED"){
layer.msg("操作失败!" + response.message);
}
},
error: function (response) {
layer.msg(response.status + " " + response.statusText);
}
})
// 关闭模态框
$("#confirmModal").modal("hide");
});
⑤ 给单条删除按钮绑定单击响应函数
// 9.给单条删除按钮绑定单击响应函数
$("#rolePageBody").on("click",".removeBtn",function () {
// 从当前按钮出发获取角色名称
var roleName = $(this).parent().prev().text();
// 创建role对象存入数组
roleArray = [{
roleId: this.id,
roleName: roleName
}];
// 调用专门的函数打开模态框
showConfirmModal(roleArray);
});
⑥ 全选 全不选的反向操作
// 11.全选 全不选的反向操作
$("#rolePageBody").on("click",".itemBox",function () {
// 获取当前已经选中的itemBox的数量
var checkBoxCount = $(".itemBox:checked").length;
// 获取全部.itemBox的数量
var totalBoxCount = $(".itemBox").length;
// 使用二者的比较结果设置总的checkBox
$("#summaryBox").prop('checked' , checkBoxCount == totalBoxCount);
});
⑦ 给批量删除的按钮绑定单击响应函数
// 12.给批量删除的按钮绑定单击响应函数
$("#batchRemoveBtn").click(function () {
// 创建一个数组对象,用来存放后面获取到的对象
var roleArray = [];
$(".itemBox:checked").each(function () {
// 使用this引用当前遍历得到的多选框
var roleId = this.id;
// 通过dom操作获取角色名称
var roleName = $(this).parent().next().text();
roleArray.push({
"roleId": roleId,
"roleName": roleName
});
});
// 检查roleArray的长度
if (roleArray.length == 0) {
layer.msg("请至少选择一个执行删除操作!")
}
// 调用执行删除操作
showConfirmModal(roleArray);
});