概述
进行角色的分页查询,保存,更新,删除操作。利用ajax向后端发起请求,再传到前端
一、角色分页查询
1.目标
将角色数据进行分页
2.思路
实现分页步骤:
- 1.写一个sql查询语句,mapper接口
- 2.service接口中的方法返回类型PageInfo<实体类> xxx(Integer pageNum,Integer pageSize)
- 3.serviceImpl实现类中
-
- PageHelper.startPage(pageNum,pageSize);//开启分页功能
-
- 调用方法开始查询返回List集合
-
- PageInfo pageInfo = new PageInfo(roles);//将查询到的结果封装到PageInfo中
- 4.编写handle
3.代码
3.1 创建数据库表
3.2 逆向生成资源
3.3 编写查询sql语句,RoleMapper接口
<!--通过关键词查询-->
<select id="selectRoleByKeyword" resultMap="BaseResultMap">
select id,name from t_role where name like concat("%",#{keyword},"%")
</select>
3.4 RoleService接口和实现,分页
RoleService接口
//通过关键词查询Role,分页,这里返回的是pageInfo
/**
* keyword:搜索的关键词信息
* pageNum:总页数
* pageSize每页显示的条数
* */
PageInfo<Role> getPageInfo(String keyword,Integer pageNum,Integer pageSize);
RoleServiceImpl实现类
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleMapper roleMapper;
/**
* 分页显示
* */
@Override
public PageInfo<Role> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {
// 1.调用PageHelper的静态方法开启分页
PageHelper.startPage(pageNum,pageSize);
// 2.通过关键词进行查询
List<Role> roles = roleMapper.selectRoleByKeyword(keyword);
// 3.将查询封装到pageInfo中
PageInfo pageInfo = new PageInfo(roles);
return pageInfo;
}
}
3.4 RoleHandle编写
/*-------------------分页功能-------------------*/
/**
* 跳转到分页页面
* */
@RequestMapping("/role/to/page.html")
public String toPage(){
return "role-page";
}
/**
* 分页功能
* */
@ResponseBody
@RequestMapping("/role/get/page/info.json")
public ResultEntity<PageInfo<Role>> getPageInfo(
@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize,
@RequestParam(value = "keyword",defaultValue = "") String keyword
){
// 1.调用Service方法获取分页数据
PageInfo<Role> pageInfo = roleService.getPageInfo(keyword, pageNum, pageSize);
// 2.封装到ResultEntity对象中返回,如果上面的操作出现异常,交给异常映射处理.
return ResultEntity.successWithData(pageInfo);
}
3.5 编写role-page.jsp
3.6 修改角色维护链接-跳转
3.7 初始化数据为分页做准备
$(function (){
// 1.为分页操作准备做初始化
window.pageNum=1;
window.pageSize=5;
window.keyword="";
// 2.调用分页的函数,显示分页结果
generatePage();
}
3.8 创建外部js文件
// 1.执行分页,生成页面效果,任何时候调用这个函数都会重新加载页面
function generatePage(){
// 1.1.获取pageInfo数据
getPageInfoRemote();
}
// 2.远程访问服务器端获取pageInfo数据
function getPageInfoRemote(){
$.ajax({
url:"role/get/page/info.json",
type:"post",
data:{
"pageNum":window.pageNum,
"pageSize":window.pageSize,
"keyword":window.keyword
},
dataType:"json",
success:function (resp){
var pageInfo = resp.data;
//console.log(pageInfo);
// 将pageInfo信息填充到表格
fillTableBody(pageInfo);
},
error:function (resp){
}
});
}
// 3.显示分页的主体数据
function fillTableBody(pageInfo){
// 3.1 清除tbody旧的数据
$("#rolePageBody").empty();
$("#Pagination").empty();
// 3.2 判断pageInfo是否有效
if (pageInfo==null||pageInfo == undefined || pageInfo.list == null || pageInfo.list.length ==0){
$("#rolePageBody").append("<tr><td colspan='4'> 抱歉,没有查询到您搜索的数据 </td><tr>");
return ;
}
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>";
// 3.3 通过button标签的id属性,把roleId值传递到button按钮的单击响应函数中
var pencilBtn = "<button id='"+roleId+"' type='button' class='btn btn-primary btn-xs pencilBtn '><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);
}
// 3.4生成分页导航条
generateNavigator(pageInfo);
}
// 4.生成分页页码导航条
function generateNavigator(pageInfo){
// 4.1. 获取总记录数
var totalRecord = pageInfo.total;
// 4.2.声明一个JSON对象存储Pagination要设置的属性
var properties={
num_edge_entries: 3, //边缘页数
num_display_entries: 5, //主体页数
callback: paginationCallBack, //指定用户点击翻页按钮时跳转页面的函数
items_per_page: pageInfo.pageSize, //每页显示的条数
current_page: pageInfo.pageNum-1, //pageNum是从1开始的,而pagination内部使用pageIndex来管理的,里面是从0开始的
prev_text: "上一页", //上一页按钮上显示的文本
next_text: "下一页" //下一页按钮上显示的文本
}
// 4.3 生成页码导航条
$("#Pagination").pagination(totalRecord,properties);
}
// 6.翻页时的回调函数
function paginationCallBack(pageIndex,jQuery){
// 6.1 修改window对象的pageNum属性
window.pageNum=pageIndex+1;
// 6.2 调用分页函数
generatePage();
// 6.3 取消页码超链接的默认行为
return false;
}
在 role-page.jsp引入外部JavaScript文件role.js, Pagination 环境
二、角色查询操作
1.目标
把页面上的“查询”表单和已经封装好的执行分页的函数连起来即可
2.思路
3.代码
3.1 增加查询id
3.2 修改role-page
三、角色保存操作
1. 目标
通过在打开的模态框中输入角色名称,执行对新角色的保存
2.思路
3.代码
3.1引入模态框
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<div id="myModal" 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 type="text" name="roleName" class="form-control" placeholder="请输入角色名称" autofocus>
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="saveRoleBtn" class="btn btn-primary">保存</button>
</div>
</div>
</div>
</div>
3.2 在 role-page.jsp 引入上面的文件
3.3 role-page代码
// 4.给新增模态框中的保存按钮添加单机响应函数
$("#saveRoleBtn").click(function (){
/**
* 获取角色名字的两种方法:
* var roleName = $.trim($("#addModal [name=roleName]").val())
* var roleName = $('input[name="roleName"]').val();
* */
// ①获取用户在文本框中输入的角色名称
// #addModal 表示找到整个模态框
// 空格表示在后代元素中继续查找
// [name=roleName]表示匹配 name 属性等于 roleName 的元素
//var roleName = $.trim($("#addModal [name=roleName]").val())
var roleName = $('input[name="roleName"]').val();
$.ajax({
url:"role/save.json",
type:"post",
data:{"name":roleName},
dataType:"json",
success:function (resp){
var result = resp.result;
if (result=="SUCCESS"){
layer.msg("操作成功!");
}
if(result=="FAILED"){
layer.msg("操作失败!"+resp.message);
}
},
error:function (resp){
layer.msg(resp.status+" "+resp.statusText);
}
});
//alert(roleName);
// 关闭模态框
$('#myModal').modal('hide');
// 清理模态框
$('input[name="roleName"]').val("");
/*// 重新加载刷新页面数据
window.keyword=roleName;
generatePage();*/
});
3.5后端代码
1.Controller
/**
* 新增角色
* */
@ResponseBody
@RequestMapping("/role/save.json")
public ResultEntity<String> addRole(@RequestParam("name") String roleName){
roleService.save(new Role(null,roleName));
return ResultEntity.successWithoutData();
}
2.Service
void save(Role role);
3.ServiceImpl
/**
* 新增角色
* */
@Override
public void save(Role role) {
roleMapper.insert(role);
}
四、角色更新操作
1.目标
角色信息更新,点击修改按钮,弹出模态框,进行更新保存。
2.思路
3.代码
3.1新建model-role-edit.jsp,加入模态框
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<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 type="text" name="roleName" class="form-control" placeholder="请输入角色名称" autofocus>
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="updateRoleBtn" class="btn btn-primary">更新</button>
</div>
</div>
</div>
</div>
3.2 在role-page.jsp引入模态框
3.3 打开模态框(回显)
3.3.1 修改role.js
var pencilBtn = "<button id='"+roleId+"' type='button' class='btn btn-primary btn-xs pencilBtn '><i class=' glyphicon glyphicon-pencil '></i></button>";
3.3.2 给铅笔绑定给单击响应函数,弹出模态框
修改role-page.jsp
// 5.给"铅笔"按钮绑定单击事件,弹出模态框
/**
* 1.首先找到所以动态生成的元素附着的静态元素
* 2.on()函数的第一个参数是事件类型
* 3.on()函数的第二个参数是找到真正要绑定事件的元素的选择器
* 4.on()函数的第三个参数是时间的响应函数
* */
$("#rolePageBody").on("click",".pencilBtn",function (){
$('#editModal').modal('show');
// 获取表格中当前行的名字
var roleName = $(this).parent().prev().text();
// 将名字传入模态框中的文本框
$("#editModal [name=roleName]").val(roleName);
// 获取当前角色的id
// 依据是:var pencilBtn = "<button id='"+roleId+"' type='button' class='btn btn-primary btn-xs pencilBtn '><i....
// 为了让更新的按钮能够获取到roleId,把他放在全局变量
window.roleId=this.id;
})
3.3.3 给模态框中的更新按钮绑定单击事件
// 6.给更新按钮绑定单击事件
$("#updateRoleBtn").click(function (){
// 获取更新后文本框中的名字
var roleName = $("#editModal [name=roleName]").val();
$.ajax({
url:"role/update.json",
type:"post",
data:{
"id":window.roleId,
"name":roleName
},
dataType: "json",
success:function (resp){
var result = resp.result;
if (result=="SUCCESS"){
layer.msg("操作成功!");
}
if(result=="FAILED"){
layer.msg("操作失败!"+resp.message);
}
},
error:function (resp){
layer.msg(resp.status+" "+resp.statusText);
}
});
$('#editModal').modal('hide');
// 重新加载刷新页面数据
generatePage();
});
});
</script>
3.3.4 后端
RoleController
/**
* 更新角色
* */
@ResponseBody
@RequestMapping("/role/update.json")
public ResultEntity<String> update(@RequestParam("id") Integer id,
@RequestParam("name") String roleName){
roleService.updateRole(new Role(id,roleName));
return ResultEntity.successWithoutData();
}
RoleService
void updateRole(Role role);
ROleServiceImpl
/**
* 更新角色
* */
@Override
public void updateRole(Role role) {
roleMapper.updateByPrimaryKey(role);
}
五、角色删除操作
1.目标
前端的“单条删除”和后端的“批量删除”合并为同一套,合并的依据时单条删除时id也放在数组中,后端完全根据id的数组进行删除
2.思路
3.代码
3.0 前端:编写模态框
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<div id="removeModal" 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" style="text-align: center">
<h4 >请确认是否要删除下列角色</h4>
<div id="roleNameDiv" >
</div>
</div>
<div class="modal-footer">
<button type="button" id="removeRoleBtn" class="btn btn-primary">确认删除</button>
</div>
</div>
</div>
</div>
3.1 前端:声明函数用于打开模态框
/*-----------------------------------删除操作---模态框--------------------------------*
/**
* 声明专门的函数显示确认模态框
* */
function showConfirmModal(roleArray){
// 1.打开模态框
$('#removeModal').modal('show');
// 2.创建一个全局的id数组
window.roleIdArray=[];
// 3.清除旧的数据
$("#roleNameDiv").empty();
// 4.遍历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;
// 5.将id存入数组中
window.roleIdArray.push(roleId);
}
}
3.2 前端:给模态框中的确认按钮删除按钮添加响应函数
role-page.jsp
// 7.点击模态框中的确认删除按钮执行删除
$("#removeRoleBtn").click(function (){
// 从全局变量范围获取roleIdArray,将json数组转为json字符串
var requestBody = JSON.stringify(window.roleIdArray);
$.ajax({
url:"role/remove/byId/array.json",
type:"post",
data:requestBody,
contentType:"application/json;charset=UTF-8",
dataType:"json",
success:function (resp){
var result = resp.result;
if (result=="SUCCESS"){
generatePage();
layer.msg("操作成功!");
}
if(result=="FAILED"){
layer.msg("操作失败!"+resp.message);
}
},
error:function (resp){
layer.msg(resp.status+" "+resp.statusText);
}
});
// 关闭模态框
$('#removeModal').modal('hide');
// 如果全选时,点击确认删除按钮后去除全选
if ($("#summaryBox").is(":checked")){
$("#summaryBox").prop("checked",false);
}
});
3.3 前端:给单条删除按钮绑定单击响应函数
role.js
var removeBtn = "<button id='"+roleId+"' type='button' class='btn btn-danger btn-xs removeBtn'><i class=' glyphicon glyphicon-remove'></i></button>";
role-page.jsp
// 8.给单条删除按钮绑定单击函数,类似上面的铅笔按钮
$("#rolePageBody").on("click",".removeBtn",function (){
// 获取表格中当前行的名字
var roleName = $(this).parent().prev().text();
// 创建role对象数组
var roleArray=[{
roleName:roleName,
roleId:this.id
}];
// 调用函数打开模态框
showConfirmModal(roleArray);
// 获取当前角色的id
// 依据是:var pencilBtn = "<button id='"+roleId+"' type='button' class='btn btn-primary btn-xs pencilBtn '><i....
// 为了让更新的按钮能够获取到roleId,把他放在全局变量
//window.roleId=this.id;
});
3.4 前端:给总的checkBox绑定单击函数
$("#summaryBox").click(function (){
// 1.获取当前多选框的自身状态
var currentStatus = this.checked;
// 2.用当前多选框的状态设置其他多选框
$(".itemBox").prop("checked",currentStatus);
});
3.5 前端:设置全选和全不选的反向操作
$("#rolePageBody").on("click",".itemBox",function (){
// 获取当前已选中的,itemBox的数量
var checkedBoxCount = $(".itemBox:checked").length;
// 获取全部itemBox的数量
var totalBoxCount = $(".itemBox").length;
// 使用二者的比较结果设置总的checkbox
$("#summaryBox").prop("checked",checkedBoxCount==totalBoxCount);
});
3.6 前端:给批量删除的按钮绑定单击函数响应函数
$("#deleteRoleModel").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 ;
}
// 调用专门的函数打开模态框
showConfirmModal(roleArray);
});
3.7 后端:RoleMapper接口
// 逆向生成的代码
int deleteByExample(RoleExample example)
3.8 后端:RoleMapper.xml
<delete id="deleteByExample" parameterType="com.hejinjie.crowd.entity.RoleExample" >
delete from t_role
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
</delete>
3.9 后端:RoleService.java接口
参数:List集合
void remove (List<Integer> roleList);
3.10 后端:RoleServiceImpl
用QBC方法,不需要写sql去动态拼接了
/**
* 使用QBC删除对象
* */
@Override
public void remove(List<Integer> roleList) {
// 使用QBC查询
// 1.创建example对象
RoleExample example = new RoleExample();
// 2.用example创建Criteria对象,Criteria是用来存储参数的
Criteria criteria = example.createCriteria();
// 3.设置id等于集合里中的值,最后生成的 where id in (5,8,12)
criteria.andIdIn(roleList);
// 4.将example作为参数传入查询方法中
roleMapper.deleteByExample(example);
}
3.11 后端:RoleController
/**
* 删除操作
* */
@ResponseBody
@RequestMapping("/role/remove/byId/array.json")
public ResultEntity<Integer> removeRoleById(@RequestBody List<Integer> roleIdList){
roleService.remove(roleIdList);
return ResultEntity.successWithoutData();
}