本笔记大多来源于尚硅谷【封捷老师讲的尚筹网项目】
尚硅谷尚筹网项目视频教程
下载链接:https://pan.baidu.com/s/1WOLG7b4yHkQfSMu3fMsOBA
提取码:s5gw
管理员增、删、改功能
代码实现:
①前端页面修改
原:
<button type="button" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i></button>
现在:
<a href="admin/del/${admin.id}/${requestScope.adminPage.pageNum}/${param.keyword}.html" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i></a>
②后台代码
idea快捷键之打开实现类:ctrl+alt+鼠标点击【左键】
handler:
@RequestMapping("/admin/del/{id}/{pageNum}/{keyword}.html") public String delAdminById( @PathVariable("id") Integer id, @PathVariable("pageNum") Integer pageNum, @PathVariable("keyword") String keyword ){ admainService.delAdminById(id); return "redirect:/admin/page.html?pageNum="+pageNum+"&keyword="+keyword; }
service:
@Override public void delAdminById(Integer id) { adminMapper.deleteByPrimaryKey(id); }
页面修改:
原:
<button type="button" class="btn btn-primary" style="float:right;" onclick="window.location.href='add.html'"><i class="glyphicon glyphicon-plus"></i> 新增</button>
现在:
<a href="admin/to/add.html" class="btn btn-primary" style="float:right;"><i class="glyphicon glyphicon-plus"></i> 新增</a>
由于不涉及带数据,直接使用view-controller进行跳转
<mvc:view-controller path="/admin/to/add.html" view-name="admin-add"/>
创建添加页面:admin-add
<%-- Created by IntelliJ IDEA. User: 25017 Date: 2020/3/24 Time: 18:18 To change this template use File | Settings | File Templates. --%> <%-- Created by IntelliJ IDEA. User: 25017 Date: 2020/3/23 Time: 12:44 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html lang="UTF-8"> <%@include file="/WEB-INF/include-head.jsp" %> <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"> <ol class="breadcrumb"> <!-- 面包屑 --> <li><a href="admin/main.html">首页</a></li> <li><a href="admin/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/add.html" method="post" role="form"> <!-- 显示异常消息 --> <p>${requestScope.exception.message}</p> <div class="form-group"> <label for="exampleInputPassword1">登陆账号</label> <input type="text" name="loginAcct" class="form-control" id="exampleInputPassword1" placeholder="请输入登陆账号"> </div> <div class="form-group"> <label for="exampleInputPassword1">登陆密码</label> <input type="text" name="userPswd" class="form-control" id="exampleInputPassword1" placeholder="请输入登陆账号"> </div> <div class="form-group"> <label for="exampleInputPassword1">用户昵称</label> <input type="text" name="userName" class="form-control" id="exampleInputPassword1" 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.com</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> </div> </div> </body> </html>
给数据库表登陆账号添加唯一约束:
ALTER TABLE `t_admin` ADD UNIQUE INDEX (`login_acct`);
注意:需要先保证表中该字段没有重复值【下面脚本如果能查询到值,应将符合条件的数据删除】:
select *,count(1) from t_admin group by login_acct having count(login_acct) > 1
自定义异常:
package com.atguigu.crowd.exception; public class AddAdminException extends RuntimeException { public AddAdminException() { super(); } public AddAdminException(String message) { super(message); } public AddAdminException(String message, Throwable cause) { super(message, cause); } public AddAdminException(Throwable cause) { super(cause); } protected AddAdminException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
handler:
@RequestMapping("admin/add.html") public String addAdmin(Admin admin){ //执行添加操作 admainService.addAdmin(admin); return "redirect:/admin/page.html?pageNum="+Integer.MAX_VALUE; }
service:
@Override public void addAdmin(Admin admin) { // 1、取得用户输入的密码 String userPswd = admin.getUserPswd(); // 2、将密码进行md5加密 userPswd = CrowdUtil.md5(userPswd); // 3、将密码重新放入admin对象 admin.setUserPswd(userPswd); // 4、获取当前时间 Date now = new Date(); // 5、将当前时间格式化 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formatNowDate = simpleDateFormat.format(now); // 6、将当前时间放入admin对象 admin.setCreateTime(formatNowDate); // 7、执行添加操作 try { adminMapper.insert(admin); }catch (Exception e){ logger.info(CrowdConstant.ADD_ADMIN_ERROR_MESSAGE); e.printStackTrace(); throw new AddAdminException(CrowdConstant.ADD_ADMIN_ERROR_MESSAGE); } }
页面:
原:
<button type="button" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i></button>
现在:
<a href="admin/update/${admin.id}.html" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i></a>
创建修改页面 admin-update:
<%-- Created by IntelliJ IDEA. User: 25017 Date: 2020/3/24 Time: 18:18 To change this template use File | Settings | File Templates. --%> <%-- Created by IntelliJ IDEA. User: 25017 Date: 2020/3/23 Time: 12:44 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html lang="UTF-8"> <%@include file="/WEB-INF/include-head.jsp" %> <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"> <ol class="breadcrumb"> <li><a href="admin/main.html">首页</a></li> <li><a href="admin/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="${admin.id}"/> <div class="form-group"> <label for="exampleInputPassword1">登陆账号</label> <input type="text" name="loginAcct" value="${admin.loginAcct}" class="form-control" id="exampleInputPassword1" placeholder="请输入登陆账号"> </div> <div class="form-group"> <label for="exampleInputPassword1">用户昵称</label> <input type="text" name="userName" value="${admin.userName}" class="form-control" id="exampleInputPassword1" placeholder="请输入用户名称"> </div> <div class="form-group"> <label for="exampleInputEmail1">邮箱地址</label> <input type="email" name="email" value="${admin.email}" class="form-control" id="exampleInputEmail1" placeholder="请输入邮箱地址"> <p class="help-block label label-warning">请输入合法的邮箱地址, 格式为: xxxx@xxxx.com</p> </div> <button type="submit" class="btn btn-success"><i class="glyphicon glyphicon-update"></i> 修改</button> <button type="reset" class="btn btn-danger"><i class="glyphicon glyphicon-refresh"></i> 重置</button> </form> </div> </div> </div> </div> </div> </body> </html>
自定义异常:
package com.atguigu.crowd.exception; public class UpdateAdminException extends RuntimeException { public UpdateAdminException() { super(); } public UpdateAdminException(String message) { super(message); } public UpdateAdminException(String message, Throwable cause) { super(message, cause); } public UpdateAdminException(Throwable cause) { super(cause); } protected UpdateAdminException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
解析异常:
package com.atguigu.crowd.mvc.config; import com.atguigu.crowd.exception.AccessForbiddenException; import com.atguigu.crowd.exception.AddAdminException; import com.atguigu.crowd.exception.LoginFailedException; import com.atguigu.crowd.exception.UpdateAdminException; import com.atguigu.crowd.util.CrowdUtil; import com.atguigu.crowd.util.ResultEntity; import com.google.gson.Gson; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @ControllerAdvice public class CrowdExceptionResolver { @ExceptionHandler(value = UpdateAdminException.class) public ModelAndView resolveUpdateAdminException( UpdateAdminException exception, HttpServletRequest request, HttpServletResponse response ) throws IOException { String viewName = "system-error"; return commonResolve(viewName, exception, request, response); } @ExceptionHandler(value = AddAdminException.class) public ModelAndView resolveAddAdminException( AddAdminException exception, HttpServletRequest request, HttpServletResponse response ) throws IOException { String viewName = "admin-add"; return commonResolve(viewName, exception, request, response); } @ExceptionHandler(value = AccessForbiddenException.class) public ModelAndView resolveAccessForbiddenExceptionException( AccessForbiddenException exception, HttpServletRequest request, HttpServletResponse response ) throws IOException { String viewName = "admin-login"; return commonResolve(viewName, exception, request, response); } @ExceptionHandler(value = LoginFailedException.class) public ModelAndView resolveLoginFailedException( LoginFailedException exception, HttpServletRequest request, HttpServletResponse response ) throws IOException { String viewName = "admin-login"; return commonResolve(viewName, exception, request, response); } @ExceptionHandler(value = ArithmeticException.class) public ModelAndView resolveMathException( ArithmeticException exception, HttpServletRequest request, HttpServletResponse response ) throws IOException { String viewName = "system-error"; return commonResolve(viewName, exception, request, response); } @ExceptionHandler(value = NullPointerException.class) public ModelAndView resolveNullPointerException( NullPointerException exception, HttpServletRequest request, HttpServletResponse response) throws IOException { String viewName = "system-error"; return commonResolve(viewName, exception, request, response); } // @ExceptionHandler将一个具体的异常类型和一个方法关联起来 private ModelAndView commonResolve( // 异常处理完成后要去的页面 String viewName, // 实际捕获到的异常类型 Exception exception, // 当前请求对象 HttpServletRequest request, // 当前响应对象 HttpServletResponse response) throws IOException { // 1.判断当前请求类型 boolean judgeResult = CrowdUtil.judgeRequestType(request); // 2.如果是Ajax请求 if(judgeResult) { // 3.创建ResultEntity对象 ResultEntity<Object> resultEntity = ResultEntity.failed(exception.getMessage()); // 4.创建Gson对象 Gson gson = new Gson(); // 5.将ResultEntity对象转换为JSON字符串 String json = gson.toJson(resultEntity); // 6.将JSON字符串作为响应体返回给浏览器 response.getWriter().write(json); // 7.由于上面已经通过原生的response对象返回了响应,所以不提供ModelAndView对象 return null; } // 8.如果不是Ajax请求则创建ModelAndView对象 ModelAndView modelAndView = new ModelAndView(); // 9.将Exception对象存入模型 modelAndView.addObject("exception", exception); // 10.设置对应的视图名称 modelAndView.setViewName(viewName); // 11.返回modelAndView对象 return modelAndView; } }
统一的出错页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html lang="UTF-8"> <%@include file="/WEB-INF/include-head.jsp" %> <body> <%@include file="/WEB-INF/include-nav.jsp" %> <!-- 从请求域取出Exception对象,再进一步访问message属性就能够显示错误消息 --> <div class="container" style="text-align: center;"> <h3>系统错误信息页面</h3> <h4>${requestScope.exception.message }</h4> <button style=" 300px;margin: 0px auto 0px auto;" class="btn btn-lg btn-success btn-block">返回刚才页面</button> </div> <script type="text/javascript"> $(function () { $("button").click(function () { // 调用 back()方法类似于点击浏览器的后退按钮 window.history.back(); }); }); </script> </body> </html>
handler:【保证中文被解析】
// 执行修改方法 @RequestMapping("/admin/update.html") public String updateAdmin(Admin admin, RedirectAttributes attributes){ admainService.updateAdminById(admin); attributes.addAttribute("keyword",admin.getLoginAcct()); return "redirect:/admin/page.html"; } // 去往修改页面 @RequestMapping("/admin/update/{id}.html") public String toUpdateAdminPage( @PathVariable("id") Integer id, ModelMap modelMap ){ Admin admin = admainService.getAdminById(id); modelMap.addAttribute("admin",admin); return "admin-update"; }
service:
// 根据id查询 @Override public Admin getAdminById(Integer id) { Admin admin = adminMapper.selectByPrimaryKey(id); return admin; } // 有选择的修改 @Override public void updateAdminById(Admin admin) { // 执行修改方法:有选择的修改 try{ adminMapper.updateByPrimaryKeySelective(admin); }catch (Exception e) { logger.info(CrowdConstant.ADMIN_UPDATE_ERROR_MESSAGE); e.printStackTrace(); throw new UpdateAdminException(CrowdConstant.ADMIN_UPDATE_ERROR_MESSAGE); } }