聚星Note05

编程入门 行业动态 更新时间:2024-10-28 18:34:08

<a href=https://www.elefans.com/category/jswz/34/1706373.html style=聚星Note05"/>

聚星Note05

聚星Note05 - 管理员维护

  • 1 分页
    • 1.1 配置 PageHelper 插件
    • 1.2 业务逻辑实现
    • 1.3 配置分页导航栏
    • 1.4 添加关键词查询
  • 2 管理员维护模块
    • 2.1 删除操作
    • 2.2 添加操作
    • 2.3 修改操作
  • 3 代码托管

1 分页

1.1 配置 PageHelper 插件

  1. gatherStars-admin-component/pom.xml 查看是否有分页插件
<!-- MyBatis 分页插件 -->
<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId>
</dependency>
  1. spring-persist-mybatis.xml 配置插件
<!-- 配置插件 -->
<property name="plugins"><array><!-- 配置 PageHelper 插件 --><bean class="com.github.pagehelper.PageHelper"><property name="properties"><props><!-- 配置数据库方言,告知 PageHelper 当前使用的数据库 --><prop key="dialect">mysql</prop><!-- 配置页码的合理化修正,用户访问不合理的页码时所做的处理 --><prop key="reasonable">true</prop></props></property></bean></array>
</property>

1.2 业务逻辑实现

  1. 创建 WEB-INF/admin-page.jsp
<%@ page contentType="text/html; charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ taglib uri="" prefix="c"%>
<!DOCTYPE html>
<html lang="zh-CN">
<%@include file="include-head.jsp" %>
<body><%@include file="include-nav.jsp"%><div class="container-fluid"><div class="row"><%@include file="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='add.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"><input type="checkbox"></th><th width="30">#</th><th>账号</th><th>名称</th><th>邮箱地址</th><th width="100">操作</th></tr></thead><tbody><c:if test="${empty requestScope.pageInfo.list }"><tr><td colspan="6" align="center">抱歉!没有查询到您要的数据!</td></tr></c:if><c:if test="${!empty requestScope.pageInfo.list }"><c:forEach items="${requestScope.pageInfo.list }" var="admin" varStatus="myStatus"><tr><td>${myStatus.count }</td><td><input type="checkbox"></td><td>${admin.loginAcct }</td><td>${admin.userName }</td><td>${admin.email }</td><td><button type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button><a href="admin/to/edit/page.html?adminId=${admin.id }&pageNum=${requestScope.pageInfo.pageNum }&keyword=${param.keyword }" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i></a><a href="admin/remove/${admin.id }/${requestScope.pageInfo.pageNum }/${param.keyword }.html" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i></a></td></tr></c:forEach></c:if></tbody><tfoot><tr ><td colspan="6" align="center"><ul class="pagination"><li class="disabled"><a href="#">上一页</a></li><li class="active"><a href="#">1 <span class="sr-only">(current)</span></a></li><li><a href="#">2</a></li><li><a href="#">3</a></li><li><a href="#">下一页</a></li></ul></td></tr></tfoot></table></div></div></div></div></div>
</div></body>
</html>
  1. com.turling.gatherStars.constant.ProjectConstant 添加常量
public static final String ATTR_NAME_PAGE_INFO = "pageInfo";
  1. com.turling.gatherStars.mvc.handler.AdminHandler 添加getPageInfo 方法
@RequestMapping("/admin/get/page.html")
public String getPageInfo(@RequestParam(value="keyword", defaultValue="") String keyword,@RequestParam(value="pageNum", defaultValue="1") Integer pageNum,@RequestParam(value="pageSize", defaultValue="5") Integer pageSize,ModelMap modelMap) {// 调用 Service 方法获取 PageInfo 对象PageInfo<Admin> pageInfo = adminService.getPageInfo(keyword, pageNum, pageSize);// 将 PageInfo 对象存入模型modelMap.addAttribute(ProjectConstant.ATTR_NAME_PAGE_INFO, pageInfo);return "admin-page";
}
  1. com.turling.gatherStars.service.api.AdminService 添加
PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize);
  1. com.turling.gatherStars.service.impl.AdminServiceImpl 添加
public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {// 1. 调用 PageHelper 的静态方法开启分页功能PageHelper.startPage(pageNum, pageSize);// 2. 执行查询List<Admin> adminList = adminMapper.selectAdminWithKeyword(keyword);// 3. 封装到 PageInfo 对象中PageInfo<Admin> adminPageInfo = new PageInfo<Admin>(adminList);return adminPageInfo;
}
  1. com.turling.gatherStars.mapper.AdminMappe 添加
List<Admin> selectAdminWithKeyword(String keyword);
  1. mybatis/mapper/AdminMapper.xml 添加
<select id="selectAdminWithKeyword" resultMap="BaseResultMap">select id, login_acct, user_pswd, user_name, email, create_timefrom t_adminwherelogin_acct like concat("%",#{keyword},"%") oruser_name like concat("%",#{keyword},"%") oremail like concat("%",#{keyword},"%")</select>

1.3 配置分页导航栏

  1. 引入文件
<%@include file="include-head.jsp" %>
<!-- 引入 pagination 所需样式 -->
<link rel="stylesheet" href="css/pagination.css"/>
<script type="text/javascript" src="jquery/jquery.pagination.js"></script>
  1. WEB-INF/admin-page.jsp 添加处理函数
<script type="text/javascript">// 函数定义:初始化页码导航条$(function () {initPagination();});// 函数实现:初始化页码导航条function initPagination() {// 获取总记录数var totalRecord = ${requestScope.pageInfo.total};// 声明 JSON 对象存储 Pagination 属性var properties = {num_edge_entries: 3,  // 边缘页数num_display_entries: 5,  // 主体页数callback: pageSelectCallback,  // 翻页回调函数items_per_page: ${requestScope.pageInfo.pageSize},  // 每页显示的数量current_page: ${requestScope.pageInfo.pageNum - 1},  // Pagination 使用 pageIndex 管理页码,从0开始,而pageNum从1开始prev_text: "上一页",  // 上一页按钮上显示的文本next_text: "下一页"  // 下一页按钮上显示的文本};// 生成页码导航条$("#Pagination").pagination(totalRecord, properties);}// 回调函数,实现页面跳转function pageSelectCallback(pageIndex, jQuery) {// 根据 pageIndex 计算得到 pageNumvar pageNum = pageIndex + 1;// 跳转页面window.location.href = "admin/get/page.html?pageNum=" + pageNum;// 取消超链接默认行为return false;}
</script>
  1. 修改 jquery/jquery.pagination.js 文件, 注释回调函数
// 所有初始化完成,绘制链接
drawLinks();
// 回调函数
// opts.callback(current_page, this);

1.4 添加关键词查询

  1. 修改表单
<form action="/admin/get/page.html" method="post" ... >
  1. 添加name属性
<input name="keyword" ... placeholder="请输入查询条件">
  1. 修改button属性
<button type="submit" ... >查询</button>
  1. 修改跳转页面的拼接get请求
window.location.href = ... + pageNum + "&keyword=${param.keyword}";

 

2 管理员维护模块

2.1 删除操作

  1. WEB-INF/admin-page.jsp 修改图标处代码
<a href="admin/remove/${admin.id }/${requestScope.pageInfo.pageNum }/${param.keyword }.html" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i>
</a>
  1. com.turling.gatherStars.mvc.handler.AdminHandler 添加 remove 方法
@RequestMapping("/admin/remove/{adminId}/{pageNum}/{keyword}.html")
public String remove(@PathVariable("adminId") Integer adminId,@PathVariable("pageNum") Integer pageNum,@PathVariable("keyword") String keyword) {// 执行删除adminService.remove(adminId);// 页面跳转,回到原页面(保持查询关键字和页码)return "redirect:/admin/get/page.html?pageNum=" + pageNum + "&keyword=" + keyword;
}
  1. com.turling.gatherStars.service.api.AdminService 添加
void remove(Integer adminId);
  1. com.turling.gatherStars.service.impl.AdminServiceImpl 添加
public void remove(Integer adminId) {adminMapper.deleteByPrimaryKey(adminId);
}

2.2 添加操作

  1. 为 login_acct 字段添加唯一约束
ALTER TABLE `gather_stars`.`t_admin` ADD UNIQUE INDEX (`login_acct`);
  1. 创建 admin-add.jsp,外部模版复制admin-page.jsp
...
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"><ol class="breadcrumb"><li><a href="/admin/to/main/page.html">首页</a></li><li><a href="/admin/get/page.html">数据列表</a></li><li class="active">新增</li></ol><div class="panel panel-default"><div class="panel-heading">表单数据<div style="float: right; cursor: pointer;" data-toggle="modal" data-target="#myModal"><i class="glyphicon glyphicon-question-sign"></i></div></div><div class="panel-body"><form action="admin/save.html" method="post" role="form"><p>${requestScope.exception.message }</p><div class="form-group"><label for="loginAcct">登录账号</label><input name="loginAcct" type="text" class="form-control" id="loginAcct" placeholder="请输入登录账号"></div><div class="form-group"><label for="userPswd">登录密码</label><input name="userPswd" type="text" class="form-control" id="userPswd" placeholder="请输入登录密码"></div><div class="form-group"><label for="userName">用户昵称</label><input name="userName" type="text" class="form-control" id="userName" placeholder="请输入用户名称"></div><div class="form-group"><label for="exampleInputEmail1">邮箱地址</label><input type="email" name="email" class="form-control" id="exampleInputEmail1" placeholder="请输入邮箱地址"><p class="help-block label label-warning">请输入合法的邮箱地址, 格式为: xxxx@xxxx</p></div><button type="submit" class="btn btn-success"> <i class="glyphicon glyphicon-plus"></i> 新增</button><button type="reset" class="btn btn-danger"><i class="glyphicon glyphicon-refresh"></i> 重置 </button></form></div></div>
</div>
...
  1. spring-web-mvc.xml配置view-controller
<mvc:view-controller path="/admin/to/add/page.html" view-name="admin-add" />
  1. com.turling.gatherStars.mvc.handler.AdminHandler 添加 save 方法
@RequestMapping("/admin/save.html")
public String save(Admin admin) {adminService.saveAdmin(admin);// 由于页码修正,会跳转到页码最大处return "redirect:/admin/get/page.html?pageNum=" + Integer.MAX_VALUE;
}
  1. com.turling.gatherStars.service.api.AdminService 添加
void saveAdmin (Admin admin);
  1. com.turling.gatherStars.service.impl.AdminServiceImpl 添加
public void saveAdmin(Admin admin) {// 封装时间Date date = new Date();SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String createTime = dateFormat.format(date);admin.setCreateTime(createTime);// 登录密码加密String source = admin.getUserPswd();String encoded = GatherStarsUtil.md5(source);admin.setUserPswd(encoded);// 保存try {adminMapper.insert(admin);} catch (Exception e) {// 处理账号重复异常if (e instanceof DuplicateKeyException) {throw new LoginAcctAlreadyInUseException(ProjectConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);}}
}
  1. 创建 com.turling.gatherStars.exception.LoginAcctAlreadyInUseException
public class LoginAcctAlreadyInUseException extends RuntimeException{private static final long serialVersionUID = 1L;public LoginAcctAlreadyInUseException() {super();}public LoginAcctAlreadyInUseException(String message) {super(message);}
}
  1. com.turling.gatherStars.mvc.config.GatherStarsExceptionResolver 添加异常处理
@ExceptionHandler(value = LoginAcctAlreadyInUseException.class)
public ModelAndView resolveLoginAcctAlreadyInUseException(LoginAcctAlreadyInUseException exception,HttpServletRequest request, HttpServletResponse response) throws IOException {String viewName = "admin-add";return commonResolve(viewName, exception, request, response);
}

2.3 修改操作

  1. WEB-INF/admin-page.jsp 修改图标处代码
<a href="admin/to/edit/page.html?adminId=${admin.id }&pageNum=${requestScope.pageInfo.pageNum }&keyword=${param.keyword }" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i>
</a>
  1. 创建 admin-edit.jsp, 根据 admin-add.jsp 修改
...
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"><ol class="breadcrumb"><li><a href="/admin/to/main/page.html">首页</a></li><li><a href="/admin/get/page.html">数据列表</a></li><li class="active">更新</li></ol><div class="panel panel-default"><div class="panel-heading">表单数据<div style="float: right; cursor: pointer;" data-toggle="modal"data-target="#myModal"><i class="glyphicon glyphicon-question-sign"></i></div></div><div class="panel-body"><form action="admin/update.html" method="post" role="form"><input type="hidden" name="id" value="${requestScope.admin.id }" /><input type="hidden" name="pageNum" value="${param.pageNum }" /><input type="hidden" name="keyword" value="${param.keyword }" /><p>${requestScope.exception.message }</p><div class="form-group"><label for="loginAcct">登录账号</label><inputname="loginAcct"value="${requestScope.admin.loginAcct }"type="text" class="form-control"id="loginAcct" placeholder="请输入登录账号"></div><div class="form-group"><label for="userName">用户昵称</label><inputname="userName"value="${requestScope.admin.userName }"type="text" class="form-control"id="userName" placeholder="请输入用户名称"></div><div class="form-group"><label for="email">邮箱地址</label><input type="email"name="email"value="${requestScope.admin.email }" class="form-control" id="email"placeholder="请输入邮箱地址"><p class="help-block label label-warning">请输入合法的邮箱地址, 格式为:xxxx@xxxx</p></div><button type="submit" class="btn btn-success"><i class="glyphicon glyphicon-edit"></i> 更新</button><button type="reset" class="btn btn-danger"><i class="glyphicon glyphicon-refresh"></i> 重置</button></form></div></div>
</div>
...
  1. com.turling.gatherStars.mvc.handler.AdminHandler 添加 toEditPage、update 方法
@RequestMapping("/admin/to/edit/page.html")
public String toEditPage(@RequestParam("adminId") Integer adminId,ModelMap modelMap) {// 1.根据 adminId 查询 Admin 对象Admin admin = adminService.getAdminById(adminId);// 2.将Admin对象存入模型modelMap.addAttribute("admin", admin);return "admin-edit";
}@RequestMapping("/admin/update.html")
public String update(Admin admin, @RequestParam("pageNum") Integer pageNum,@RequestParam("keyword") String keyword) {adminService.update(admin);return "redirect:/admin/get/page.html?pageNum=" + pageNum + "&keyword=" + keyword;
}
  1. com.turling.gatherStars.service.api.AdminService 添加
Admin getAdminById(Integer adminId);
void update(Admin admin);
  1. com.turling.gatherStars.service.impl.AdminServiceImpl 添加
public Admin getAdminById(Integer adminId) {return adminMapper.selectByPrimaryKey(adminId);
}public void update(Admin admin) {//  Selective 表示有选择的更新,不更新 null 值的字段try {adminMapper.updateByPrimaryKeySelective(admin);} catch (Exception e) {if(e instanceof DuplicateKeyException) {throw new LoginAcctAlreadyInUseForUpdateException(ProjectConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);}}
}
  1. 创建 com.turling.gatherStars.exception.LoginAcctAlreadyInUseForUpdateException
public class LoginAcctAlreadyInUseForUpdateException extends RuntimeException{private static final long serialVersionUID = 1L;public LoginAcctAlreadyInUseForUpdateException() {super();}public LoginAcctAlreadyInUseForUpdateException(String message) {super(message);}
}
  1. com.turling.gatherStars.mvc.config.GatherStarsExceptionResolver 添加异常处理
@ExceptionHandler(value = LoginAcctAlreadyInUseForUpdateException.class)
public ModelAndView resolveLoginAcctAlreadyInUseForUpdateException(LoginAcctAlreadyInUseForUpdateException exception, HttpServletRequest request, HttpServletResponse response) throws IOException {String viewName = "system-error";return commonResolve(viewName, exception, request, response);
}

 

3 代码托管

将代码 push 到 git@gitee:turling/gather-stars.git

 

更多推荐

聚星Note05

本文发布于:2024-02-08 20:16:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1674587.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:聚星

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!