七 角色维护
git checkout -b 7.0.0_role
1. 角色分页
1.1 目标
- 将角色数据进行分页显示
1.2 思路
1.3 代码
1.3.1 数据库表
CREATE TABLE `project_crowd`.`t_role`
(
id INT NOT NULL auto_increment,
name CHAR(100),
PRIMARY KEY (id)
);
1.3.2 逆向生成资源 - generatorConfig.xml
<table tableName="t_role" domainObjectName="Role">
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- mybatis-generator:generate -->
<context id="atguiguTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- 数据库连接的信息: 驱动类、连接地址、用户名、密码 -->
<jdbcConnection
driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://175.178.174.83:3306/project_crowd"
userId="root"
password="root"/>
<!-- 默认 false. 把 JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,
为 true 时把 JDBC DECIMAL 和 NUMERIC 类型解析为 java.math.BigDecimal-->
<javaTypeResolver>
<property name="forceBigDeecimals" value="false"/>
</javaTypeResolver>
<!-- targetProject: 生成 Entity 类的路径 -->
<javaModelGenerator targetProject="./src/main/java"
targetPackage="com.atguigu.crowd.entity"
>
<!-- enableSubPackages: 是否让 schema 作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- targetProject: XxxMapper.xml 映射文件生成的路径 -->
<sqlMapGenerator targetProject="./src/main/java"
targetPackage="com.atguigu.crowd.mapper">
<!-- enableSubPackages: 是否让 schema 作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- targetPackage: Mapper 接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetProject="./src/main/java"
targetPackage="com.atguigu.crowd.mapper"
>
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 数据库表名字和我们的 entity 类对应的映射指定 -->
<!-- <table tableName="t_admin" domainObjectName="Admin"/>-->
<table tableName="t_role" domainObjectName="Role"/>
</context>
</generatorConfiguration>
- 执行命令
- 构造函数和toString
package com.atguigu.crowd.entity;
public class Role {
private Integer id;
private String name;
public Role() {
}
public Role(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
- 复制到该在的位置
1.3.3 SQL 语句
<!-- 自定义区域 start -->
<select id="selectRoleByKeyword" resultMap="BaseResultMap">
select id, name
from t_role
where name like concat("%", #{keyword}, "%")
</select>
<!-- 自定义区域 end -->
- RoleMapper
List<Role> selectRoleByKeyword(String keyword);
1.3.4 RoleServiceImpl
package com.atguigu.crowd.service.impl;
import com.atguigu.crowd.entity.Role;
import com.atguigu.crowd.mapper.RoleMapper;
import com.atguigu.crowd.service.api.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleMapper roleMapper;
@Override
public PageInfo<Role> getPageInfo(Integer pageNum, Integer pageSize, String keyword) {
// 1. 开启分页功能
PageHelper.startPage(pageNum, pageSize);
// 2. 执行查询
List<Role> roleList = roleMapper.selectRoleByKeyword(keyword);
// 3. 返回 PageInfo 对象
return new PageInfo<>(roleList);
}
}
1.3.5 RoleHandler
package com.atguigu.crowd.mvc.handler;
import com.atguigu.crowd.entity.Role;
import com.atguigu.crowd.service.api.RoleService;
import com.atguigu.crowd.util.ResultEntity;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class RoleHandler {
@Autowired
private RoleService roleService;
@ResponseBody
@RequestMapping("/role/get/page/info.json")
public ResultEntity<PageInfo<Role>> Test(
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "keyword", defaultValue = "") String keyword
) {
// 调用 Service 方法获取分页数据
PageInfo<Role> pageInfo = roleService.getPageInfo(pageNum, pageSize, keyword);
// 封装到 ResultEntity 对象中返回(如果上面的操作抛出异常, 交给异常映射机制处理)
return ResultEntity.successWithData(pageInfo);
}
}
package com.atguigu.crowd.mvc.handler;
import com.atguigu.crowd.entity.Role;
import com.atguigu.crowd.service.api.RoleService;
import com.atguigu.crowd.util.ResultEntity;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class RoleHandler {
@Autowired
private RoleService roleService;
@RequestMapping("/role/get/page/info.json")
public ResultEntity<PageInfo<Role>> Test(
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "keyword", defaultValue = "") String keyword
) {
// 调用 Service 方法获取分页数据
PageInfo<Role> pageInfo = roleService.getPageInfo(pageNum, pageSize, keyword);
// 封装到 ResultEntity 对象中返回(如果上面的操作抛出异常, 交给异常映射机制处理)
return ResultEntity.successWithData(pageInfo);
}
}
1.3.6 页面
spring-web-mvc.mxl
<mvc:view-controller path="/role/to/page.html" view-name="role-page" />
include-sidebar.jsp
跳转链接
<a href="role/to/page.html"><i class="glyphicon glyphicon-king"></i> 角色维护</a>
- role-page.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zn-CN">
<%@include file="/WEB-INF/include-head.jsp" %>
<link rel="stylesheet" href="css/pagination.css"/>
<script type="text/javascript" src="jquery/jquery.pagination.js"></script>
<script src="crowd/js/my-role.js" type="text/javascript"></script>
<body>
<%@include file="/WEB-INF/include-nav.jsp" %>
<div class="container-fluid">
<div class="row">
<%@include file="/WEB-INF/include-sidebar.jsp" %>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><i class="glyphicon glyphicon-th"></i> 数据列表</h3>
</div>
<div class="panel-body">
<form class="form-inline" role="form" style="float:left;">
<div class="form-group has-feedback">
<div class="input-group">
<div class="input-group-addon">查询条件</div>
<input class="form-control has-success" type="text" placeholder="请输入查询条件">
</div>
</div>
<button type="button" class="btn btn-warning"><i class="glyphicon glyphicon-search"></i> 查询
</button>
</form>
<button type="button" class="btn btn-danger" style="float:right;margin-left:10px;"><i
class=" glyphicon glyphicon-remove"></i> 删除
</button>
<button type="button" class="btn btn-primary" style="float:right;"
onclick="window.location.href='form.html'"><i class="glyphicon glyphicon-plus"></i> 新增
</button>
<br>
<hr style="clear:both;">
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th width="30">#</th>
<th width="30"><input type="checkbox"></th>
<th>名称</th>
<th width="100">操作</th>
</tr>
</thead>
<tbody id="rolePageBody">
<%-- <tr>--%>
<%-- <td>1</td>--%>
<%-- <td><input type="checkbox"></td>--%>
<%-- <td>PM - 项目经理</td>--%>
<%-- <td>--%>
<%-- <button type="button" class="btn btn-success btn-xs"><i--%>
<%-- class=" glyphicon glyphicon-check"></i></button>--%>
<%-- <button type="button" class="btn btn-primary btn-xs"><i--%>
<%-- class=" glyphicon glyphicon-pencil"></i></button>--%>
<%-- <button type="button" class="btn btn-danger btn-xs"><i--%>
<%-- class=" glyphicon glyphicon-remove"></i></button>--%>
<%-- </td>--%>
<%-- </tr>--%>
</tbody>
<tfoot>
<tr>
<td colspan="6" align="center">
<div id="Pagination" class="pagination"> <!-- 这里显示分页 --> </div>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
my-role.js
$(function () {
// 1. 为分页操作准备初始化数据
window.pageNum = 1;
window.pageSize = 5;
window.keyword = "";
generatePage();
})
// 执行分页, 生成页面效果, 如何时候调用这个函数都会重新加载页面
function generatePage() {
// 1. 获取分页数据
var pageInfo = getPageInfoRemote();
// 2. 填充表格
fillTableBody(pageInfo);
// 3. 生成分页页码导航条
generateNavigator(pageInfo);
}
// 获取分页数据
function getPageInfoRemote() {
var result = '';
$.ajax({
url: 'role/get/page/info.json',
type: 'post',
data: {
pageNum: window.pageNum,
pageSize: window.pageSize,
keyword: window.keyword
},
dateType: 'json',
async: false,
success: function (response) {
if (response.result === 'SUCCESS') {
result = response.data;
} else if (response.result === 'FAILED') {
layer.msg(response.message);
}
},
error: function (response) {
layer.msg("请求失败! 状态码=" + response.status + " 声明信息=" + response.statusText);
}
});
return result;
}
// 填充表格
function fillTableBody(pageInfo) {
// 清除 tbody 中的就数据
$("#rolePageBody").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 null;
}
// 填充 tbody
for (var i = 0; i < pageInfo.list.length; i++) {
var role = pageInfo.list[i];
var roleId = role.id;
var roleName = role.name;
$("#rolePageBody").append(`
<tr>
<td>${i + 1}</td>
<td><input type="checkbox"/></td>
<td>${roleName}</td>
<td>
<button type="button" class="btn btn-success btn-xs"><i
class=" glyphicon glyphicon-check"></i></button>
<button type="button" class="btn btn-primary btn-xs"><i
class=" glyphicon glyphicon-pencil"></i></button>
<button type="button" class="btn btn-danger btn-xs"><i
class=" glyphicon glyphicon-remove"></i></button>
</td>
</tr>
`)
}
}
// 生成分页页码导航条
function generateNavigator(pageInfo) {
// 获取总记录数
var totalRecord = pageInfo.total;
// 声明一个 JSON 对象存储 Pagination 的配置
const properties = {
// 边缘页数
num_edge_entries: 3,
// 主体页数
num_display_entries: 5,
// 监听"翻页"事件, 跳转页面时触发的函数
callback: pageSelectCallback,
// 每页显示的数据的数量
items_per_page: pageInfo.pageSize,
// Pagination 内部使用 pageIndex 来管理页码, pageIndex 从 0 开始, pageNum 从 1 开始, 所以要减1
current_page: pageInfo.pageNum - 1,
// 上一页按钮上显示的文本
prev_text: "上一页",
// 下一页按钮上显示的文本
next_text: "下一页"
}
// 生成分页
$("#Pagination").pagination(totalRecord, properties);
}
// 翻页时的回调函数
function pageSelectCallback(pageIndex, JQuery) {
// 修改 window 对象的 pageNum 属性
window.pageNum = pageIndex + 1;
// 调用分页函数
generatePage();
// 取消超链接的默认行为
return false;
}
1.3.7 关键词查询
role-page.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zn-CN">
<%@include file="/WEB-INF/include-head.jsp" %>
<link rel="stylesheet" href="css/pagination.css"/>
<script type="text/javascript" src="jquery/jquery.pagination.js"></script>
<script src="crowd/js/my-role.js" type="text/javascript"></script>
<body>
<%@include file="/WEB-INF/include-nav.jsp" %>
<div class="container-fluid">
<div class="row">
<%@include file="/WEB-INF/include-sidebar.jsp" %>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><i class="glyphicon glyphicon-th"></i> 数据列表</h3>
</div>
<div class="panel-body">
<form class="form-inline" role="form" style="float:left;">
<div class="form-group has-feedback">
<div class="input-group">
<div class="input-group-addon">查询条件</div>
<input id="keywordInput" class="form-control has-success" type="text" placeholder="请输入查询条件">
</div>
</div>
<button id="searchBtn" type="button" class="btn btn-warning"><i class="glyphicon glyphicon-search"></i> 查询
</button>
</form>
<button type="button" class="btn btn-danger" style="float:right;margin-left:10px;"><i
class=" glyphicon glyphicon-remove"></i> 删除
</button>
<button type="button" class="btn btn-primary" style="float:right;"
onclick="window.location.href='form.html'"><i class="glyphicon glyphicon-plus"></i> 新增
</button>
<br>
<hr style="clear:both;">
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th width="30">#</th>
<th width="30"><input type="checkbox"></th>
<th>名称</th>
<th width="100">操作</th>
</tr>
</thead>
<tbody id="rolePageBody">
<%-- <tr>--%>
<%-- <td>1</td>--%>
<%-- <td><input type="checkbox"></td>--%>
<%-- <td>PM - 项目经理</td>--%>
<%-- <td>--%>
<%-- <button type="button" class="btn btn-success btn-xs"><i--%>
<%-- class=" glyphicon glyphicon-check"></i></button>--%>
<%-- <button type="button" class="btn btn-primary btn-xs"><i--%>
<%-- class=" glyphicon glyphicon-pencil"></i></button>--%>
<%-- <button type="button" class="btn btn-danger btn-xs"><i--%>
<%-- class=" glyphicon glyphicon-remove"></i></button>--%>
<%-- </td>--%>
<%-- </tr>--%>
</tbody>
<tfoot>
<tr>
<td colspan="6" align="center">
<div id="Pagination" class="pagination"> <!-- 这里显示分页 --> </div>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
my-role.js
$(function () {
// 1. 为分页操作准备初始化数据
window.pageNum = 1;
window.pageSize = 5;
window.keyword = "";
// 调用执行分页函数, 显示分页效果
generatePage();
// 给查询按钮绑定点击响应函数
$("#searchBtn").click(function(){
// 获取关键词数据赋值给对应的全局变量
window.keyword = $("#keywordInput").val();
// 刷新数据
generatePage();
})
})
1.3.8 新增功能
- 目标
1.3.8.1 模态框
- 静态实例
modal-role-add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<div 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">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
<!-- /.modal -->
- 修改为新增模态框
<%@ 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 id="loginForm"
class="form-signin" role="form">
<div class="form-group has-success has-feedback">
<input type="text" class="form-control"
name="roleName" placeholder="请输入角色名称"
style="ime-mode: disabled">
</div>
</form>
</div>
<div class="modal-footer">
<button id="saveRoleBtn" type="button" class="btn btn-primary">保存</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
<!-- /.modal -->
- 引入模态框
<%@include file="/WEB-INF/modal-role-add.jsp"%>
1.3.8.2 打开模态框
<button id="showAddModalBtn" type="button" class="btn btn-primary" style="float:right;"
><i class="glyphicon glyphicon-plus"></i> 新增
</button>
// 点击新增按钮打开模态框
$('#showAddModalBtn').click(function(){
$('#addModal').model('show');
});
1.3.8.3 单击保存按钮发送请求
// 监听单击事件 - 保存模态框中的保存按钮
$('#saveRoleBtn').click(function () {
// 获取用户在输入框中输入的角色名称
// #addModal: 找到添加模态框
// 空格表示在后代元素中继续查找
// [name=roleName] 表示匹配 name 属性名为 roleName 的
var roleName = $.trim($('#addModal [name=roleName]').val());
// 发送 ajax 请求
$.ajax({
url: 'role/save.json',
type: 'post',
data: {
name: roleName
},
dateType: 'json',
success: function (response) {
if (response.result === 'SUCCESS') {
layer.msg('操作成功!');
// 关闭模态框
$('#addModal').modal('hide');
// 清理模态框
$('#addModal [name=roleName]').val('');
// 重新加载分页
window.pageNum = 99999999;
generatePage();
} else if (response.result === 'FAILED') {
layer.msg('操作失败! ' + response.message);
}
},
error: function (response) {
layer.msg(response.status + ' ' + response.statusText)
}
})
});
1.3.8.4 后台代码
- Handler
/**
* 保存角色
*
* @param role
* @return
*/
@ResponseBody
@RequestMapping("/role/save.json")
public ResultEntity<String> saveRole(Role role){
roleService.saveRole(role);
return ResultEntity.successWithoutData();
}
- ServiceImpl
@Override
public void saveRole(Role role) {
roleMapper.insert(role);
}
1.3.9 更新功能
1.3.9.1 目标
- 修改角色信息
1.3.9.2 思路
1.3.9.3 前端代码
- 引入
my-role.js
// 使用 JQuery对象的 on() 函数`动态`绑定点击事件
$('#rolePageBody').on('click', '.pencilBtn', function () {
// 打开模态框
$('#editModal').modal('show');
// 获取表格中当前行中的角色名称
var roleName = $(this).parent().prev().text();
// 获取当前元素的id - 角色id
window.roleId = this.id;
// 给模态框中的文本框赋值角色名称
$('#editModal input[name=roleName]').val(roleName);
});
$('#updateRoleBtn').click(function () {
var roleName = $('#editModal input[name=roleName]').val();
// 发送 ajax 请求
$.ajax({
url: 'role/update.json',
type: 'post',
data: {
id: window.roleId,
name: roleName
},
dateType: 'json',
success: function (response) {
if (response.result === 'SUCCESS') {
layer.msg('操作成功!');
// 关闭模态框
$('#editModal').modal('hide');
// 重新加载分页
generatePage();
} else if (response.result === 'FAILED') {
layer.msg('操作失败! ' + response.message);
}
},
error: function (response) {
layer.msg(response.status + ' ' + response.statusText)
}
})
});
1.3.9.4 后端代码
- handler
/**
* 修改角色信息
*
* @param role
* @return
*/
@ResponseBody
@RequestMapping("/role/update.json")
public ResultEntity<String> updateRole(Role role){
roleService.updateRole(role);
return ResultEntity.successWithoutData();
}
- ServiceImpl
@Override
public void updateRole(Role role) {
roleMapper.updateByPrimaryKey(role);
}
1.3.10 删除功能
1.3.10.1 目标
- 前端的 “单条删除” 和 “批量删除” 在后端合并为同一套操作。合并的依据是: 单条删除和批量删除都将 id 放在数组中, 后端完全根据 id 的数组进行删除
1.3.10.2 思路
1.3.10.3 后端代码
- Handler
@ResponseBody
@RequestMapping("/role/remove/by/role/id/array.json")
public ResultEntity<String> removeByRoleIdArray(@RequestBody List<Integer> roleList){
roleService.removeRole(roleList);
return ResultEntity.successWithoutData();
}
- ServiceImpl
@Override
public void removeRole(List<Integer> roleList) {
RoleExample roleExample = new RoleExample();
RoleExample.Criteria criteria = roleExample.createCriteria();
// delete from t_role where id in (5,8,12)
criteria.andIdIn(roleList);
roleMapper.deleteByExample(roleExample);
}
1.3.10.4 前端代码
my-role.js
// 声明专门的函数显示确认模态框
function showConfirmModal(roleArray) {
// 打开模态框
$('#confirmModal').modal('show');
// 清除旧数据
$('#roleNameDiv').empty();
// 在全局变量范围创建数组用来存放角色 id
window.roleIdArray = [];
// 遍历 roleArray 数组
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);
}
}
$('#removeRoleBtn').click(function () {
// 从全局本来那个范围获取 roleIdArray, 转换 JSON 字符串
var requestBody = JSON.stringify(window.roleIdArray);
$.ajax({
url: 'role/remove/by/role/id/array.json',
type: 'post',
data: requestBody,
contentType: 'application/json;charset=UTF-8'
dataType: 'json',
success: function (response) {
if (response.result === 'SUCCESS') {
layer.msg('操作成功!');
// 关闭模态框
$('#confirmModal').modal('hide');
// 重新加载分页
generatePage();
// 设置取消全选选项
$('#summaryBox').prop('cehcked', false);
} else if (response.result === 'FAILED') {
layer.msg('操作失败! ' + response.message);
}
},
error: function (response) {
layer.msg(response.status + ' ' + response.statusText)
}
})
})
modal-role-confirm.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>
- 单条删除
<button id="${roleId}" type="button" class="btn btn-danger btn-xs removeBtn"><i
class=" glyphicon glyphicon-remove"></i></button>
// 单条删除
$('#rolePageBody').on('click','.removeBtn', function(){
// 从当前按钮出发获取角色名称
var roleName = $(this).parent().prev().text();
// 创建 role 对象传入数组
var roleArray = [{
roleId: this.id,
roleName: roleName
}]
// 调用确认删除模态框函数
showConfirmModal(roleArray);
})
-
批量删除
-
- 全选与不全选功能
-
-
- 全选按钮设置 id 为 summaryBox
-
<th width="30"><input type="checkbox" id="summaryBox"></th>
<td><input type="checkbox" class="itemBox"/></td>
-
-
- 给总的 checkbox 绑定单击响应函数
-
// 给总的 checkbox 绑定单击响应函数
$('#summaryBox').click(function(){
// 获取当前多选框自身的状态
var currentStatus = this.checked;
// 调用当前多选框的状态设置其他多选框
$('.itemBox').prop('checked', currentStatus);
})
-
- 全选和不全选的反向操作
// 全选和不全选的反向操作
$('#rolePageBody').on('click','.itemBox',function(){
// 获取当前已经选中的 .itemBox 的数量
var checkedBoxCount = $('.itemBox:checked').length;
// 获取全部 .itemBox 的数量
var totalBoxCount = $('.itemBox').length;
// 使用二者的比较结果设置总的 checkbox
$('#summaryBox').prop('checked', checkedBoxCount === totalBoxCount);
})
-
- 给批量删除按钮绑定单击响应函数
// 给批量删除按钮绑定单击响应函数
$('#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 的长度是否为 0
if(roleArray.length === 0){
layer.msg('请至少选择一条数据!')
return false;
}
// 调用确认删除模态框函数
showConfirmModal(roleArray);
})
<button id="batchRemoveBtn" type="button" class="btn btn-danger" style="float:right;margin-left:10px;"><i
class=" glyphicon glyphicon-remove"></i> 删除
</button>
my-role.js
$(function () {
// 1. 为分页操作准备初始化数据
window.pageNum = 1;
window.pageSize = 5;
window.keyword = "";
// 调用执行分页函数, 显示分页效果
generatePage();
// 给查询按钮绑定点击响应函数
$("#searchBtn").click(function () {
// 获取关键词数据赋值给对应的全局变量
window.keyword = $("#keywordInput").val();
// 刷新数据
generatePage();
})
// 点击新增按钮打开模态框
$('#showAddModalBtn').click(function () {
$('#addModal').modal('show');
});
// 监听单击事件 - 保存模态框中的保存按钮
$('#saveRoleBtn').click(function () {
// 获取用户在输入框中输入的角色名称
// #addModal: 找到添加模态框
// 空格表示在后代元素中继续查找
// [name=roleName] 表示匹配 name 属性名为 roleName 的
var roleName = $.trim($('#addModal [name=roleName]').val());
// 发送 ajax 请求
$.ajax({
url: 'role/save.json',
type: 'post',
data: {
name: roleName
},
dateType: 'json',
success: function (response) {
if (response.result === 'SUCCESS') {
layer.msg('操作成功!');
// 关闭模态框
$('#addModal').modal('hide');
// 清理模态框
$('#addModal [name=roleName]').val('');
// 重新加载分页
window.pageNum = 99999999;
generatePage();
} else if (response.result === 'FAILED') {
layer.msg('操作失败! ' + response.message);
}
},
error: function (response) {
layer.msg(response.status + ' ' + response.statusText)
}
})
});
// 使用 JQuery对象的 on() 函数`动态`绑定点击事件
$('#rolePageBody').on('click', '.pencilBtn', function () {
// 打开模态框
$('#editModal').modal('show');
// 获取表格中当前行中的角色名称
var roleName = $(this).parent().prev().text();
// 获取当前元素的id - 角色id
window.roleId = this.id;
// 给模态框中的文本框赋值角色名称
$('#editModal input[name=roleName]').val(roleName);
});
$('#updateRoleBtn').click(function () {
var roleName = $('#editModal input[name=roleName]').val();
// 发送 ajax 请求
$.ajax({
url: 'role/update.json',
type: 'post',
data: {
id: window.roleId,
name: roleName
},
dateType: 'json',
success: function (response) {
if (response.result === 'SUCCESS') {
layer.msg('操作成功!');
// 关闭模态框
$('#editModal').modal('hide');
// 重新加载分页
generatePage();
} else if (response.result === 'FAILED') {
layer.msg('操作失败! ' + response.message);
}
},
error: function (response) {
layer.msg(response.status + ' ' + response.statusText)
}
})
});
// showConfirmModal([{roleName:'role1'},{roleName:'role2'}]);
// 声明专门的函数显示确认模态框
function showConfirmModal(roleArray) {
// 打开模态框
$('#confirmModal').modal('show');
// 清除旧数据
$('#roleNameDiv').empty();
// 在全局变量范围创建数组用来存放角色 id
window.roleIdArray = [];
// 遍历 roleArray 数组
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);
}
}
$('#removeRoleBtn').click(function () {
// 从全局本来那个范围获取 roleIdArray, 转换 JSON 字符串
var requestBody = JSON.stringify(window.roleIdArray);
$.ajax({
url: 'role/remove/by/role/id/array.json',
type: 'post',
data: requestBody,
contentType: 'application/json;charset=UTF-8',
dataType: 'json',
success: function (response) {
if (response.result === 'SUCCESS') {
layer.msg('操作成功!');
// 关闭模态框
$('#confirmModal').modal('hide');
// 重新加载分页
generatePage();
} else if (response.result === 'FAILED') {
layer.msg('操作失败! ' + response.message);
}
},
error: function (response) {
layer.msg(response.status + ' ' + response.statusText)
}
})
})
// 单条删除
$('#rolePageBody').on('click','.removeBtn', function(){
// 从当前按钮出发获取角色名称
var roleName = $(this).parent().prev().text();
// 创建 role 对象传入数组
var roleArray = [{
roleId: this.id,
roleName: roleName
}]
// 调用确认删除模态框函数
showConfirmModal(roleArray);
})
// 给总的 checkbox 绑定单击响应函数
$('#summaryBox').click(function(){
// 获取当前多选框自身的状态
var currentStatus = this.checked;
// 调用当前多选框的状态设置其他多选框
$('.itemBox').prop('checked', currentStatus);
})
// 全选和不全选的反向操作
$('#rolePageBody').on('click','.itemBox',function(){
// 获取当前已经选中的 .itemBox 的数量
var checkedBoxCount = $('.itemBox:checked').length;
// 获取全部 .itemBox 的数量
var totalBoxCount = $('.itemBox').length;
// 使用二者的比较结果设置总的 checkbox
$('#summaryBox').prop('checked', checkedBoxCount === totalBoxCount);
})
// 给批量删除按钮绑定单击响应函数
$('#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 的长度是否为 0
if(roleArray.length === 0){
layer.msg('请至少选择一条数据!')
return false;
}
// 调用确认删除模态框函数
showConfirmModal(roleArray);
})
})
// 执行分页, 生成页面效果, 如何时候调用这个函数都会重新加载页面
function generatePage() {
// 1. 获取分页数据
var pageInfo = getPageInfoRemote();
// 2. 填充表格
fillTableBody(pageInfo);
// 3. 生成分页页码导航条
generateNavigator(pageInfo);
}
// 获取分页数据
function getPageInfoRemote() {
var result = '';
$.ajax({
url: 'role/get/page/info.json',
type: 'post',
data: {
pageNum: window.pageNum,
pageSize: window.pageSize,
keyword: window.keyword
},
dateType: 'json',
async: false,
success: function (response) {
if (response.result === 'SUCCESS') {
result = response.data;
} else if (response.result === 'FAILED') {
layer.msg(response.message);
}
},
error: function (response) {
layer.msg("请求失败! 状态码=" + response.status + " 声明信息=" + response.statusText);
}
});
return result;
}
// 填充表格
function fillTableBody(pageInfo) {
// 清除 tbody 中的就数据
$("#rolePageBody").empty();
// 判 pageInfo 是否有效
if (pageInfo === null || pageInfo === undefined || pageInfo.list === null || pageInfo.list.length === 0) {
$("#rolePageBody").append("<tr><td align='center' colspan='4'>抱歉! 没有查询到您搜索的数据!</td></tr>")
return null;
}
// 填充 tbody
for (var i = 0; i < pageInfo.list.length; i++) {
var role = pageInfo.list[i];
var roleId = role.id;
var roleName = role.name;
$("#rolePageBody").append(`
<tr>
<td>${i + 1}</td>
<td><input id="${roleId}" type="checkbox" class="itemBox"/></td>
<td>${roleName}</td>
<td>
<button type="button" class="btn btn-success btn-xs"><i
class=" glyphicon glyphicon-check"></i></button>
<button id="${roleId}" type="button" class="btn btn-primary btn-xs pencilBtn"><i
class=" glyphicon glyphicon-pencil"></i></button>
<button id="${roleId}" type="button" class="btn btn-danger btn-xs removeBtn"><i
class=" glyphicon glyphicon-remove"></i></button>
</td>
</tr>
`)
}
}
// 生成分页页码导航条
function generateNavigator(pageInfo) {
// 获取总记录数
var totalRecord = pageInfo.total;
// 声明一个 JSON 对象存储 Pagination 的配置
const properties = {
// 边缘页数
num_edge_entries: 3,
// 主体页数
num_display_entries: 5,
// 监听"翻页"事件, 跳转页面时触发的函数
callback: pageSelectCallback,
// 每页显示的数据的数量
items_per_page: pageInfo.pageSize,
// Pagination 内部使用 pageIndex 来管理页码, pageIndex 从 0 开始, pageNum 从 1 开始, 所以要减1
current_page: pageInfo.pageNum - 1,
// 上一页按钮上显示的文本
prev_text: "上一页",
// 下一页按钮上显示的文本
next_text: "下一页"
}
// 生成分页
$("#Pagination").pagination(totalRecord, properties);
}
// 翻页时的回调函数
function pageSelectCallback(pageIndex, JQuery) {
// 修改 window 对象的 pageNum 属性
window.pageNum = pageIndex + 1;
// 调用分页函数
generatePage();
// 取消超链接的默认行为
return false;
}
// 声明专门的函数显示确认模态框
function showConfirmModal(roleArray) {
// 打开模态框
$('#confirmModal').modal('show');
// 清除旧数据
$('#roleNameDiv').empty();
// 在全局变量范围创建数组用来存放角色 id
window.roleIdArray = [];
// 遍历 roleArray 数组
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
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zn-CN">
<%@include file="/WEB-INF/include-head.jsp" %>
<link rel="stylesheet" href="css/pagination.css"/>
<script type="text/javascript" src="jquery/jquery.pagination.js"></script>
<script src="crowd/js/my-role.js?v=6" type="text/javascript"></script>
<body>
<%@include file="/WEB-INF/include-nav.jsp" %>
<div class="container-fluid">
<div class="row">
<%@include file="/WEB-INF/include-sidebar.jsp" %>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><i class="glyphicon glyphicon-th"></i> 数据列表</h3>
</div>
<div class="panel-body">
<form class="form-inline" role="form" style="float:left;">
<div class="form-group has-feedback">
<div class="input-group">
<div class="input-group-addon">查询条件</div>
<input id="keywordInput" class="form-control has-success" type="text"
placeholder="请输入查询条件">
</div>
</div>
<button id="searchBtn" type="button" class="btn btn-warning"><i
class="glyphicon glyphicon-search"></i> 查询
</button>
</form>
<button id="batchRemoveBtn" type="button" class="btn btn-danger" style="float:right;margin-left:10px;"><i
class=" glyphicon glyphicon-remove"></i> 删除
</button>
<button id="showAddModalBtn" type="button" class="btn btn-primary" style="float:right;"
><i class="glyphicon glyphicon-plus"></i> 新增
</button>
<br>
<hr style="clear:both;">
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th width="30">#</th>
<th width="30"><input type="checkbox" id="summaryBox"></th>
<th>名称</th>
<th width="100">操作</th>
</tr>
</thead>
<tbody id="rolePageBody">
</tbody>
<tfoot>
<tr>
<td colspan="6" align="center">
<div id="Pagination" class="pagination"> <!-- 这里显示分页 --> </div>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<%@include file="/WEB-INF/modal-role-add.jsp" %>
<%@include file="/WEB-INF/modal-role-edit.jsp" %>
<%@include file="/WEB-INF/modal-role-confirm.jsp" %>
</body>
</html>