尚筹网项目02-登录和用户模块

1.用户登录

1.1思路

在这里插入图片描述

1.2 创建一个加密的工具方法

代码

    public static String encode(String source){

        // 1.判断字符串是否合法
        if(source == null || source.length() == 0){
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_ILLEGAL);
        }

        try {
            // 2.创建MessageDigest对象
            String algorithm = "md5";
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);

            // 3.获取明文字符的字符数组
            byte[] input = source.getBytes();

            // 4.执行加密
            byte[] output = messageDigest.digest(input);

            // 5.将加密后的字符数组转换成BigInteger对象
            BigInteger bigInteger = new BigInteger(1, output);

            // 6.将bigInterger对象安装16进制转换成字符串
            String encode = bigInteger.toString(16).toUpperCase();

            return encode;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }


        return null;
    }

1.3前端代码

①登录的页面

代码

<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="keys" content="">
    <meta name="author" content="">
    <base href="http://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">
    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <link rel="stylesheet" href="css/login.css">
    <script type="text/javascript" src="jquery/jquery-2.1.1.min.js"></script>
    <script type="text/javascript" src="layer/layer.js"></script>
    <style>

    </style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <div><a class="navbar-brand" href="index.html" style="font-size:32px;">尚筹网-创意产品众筹平台</a></div>
        </div>
    </div>
</nav>
<div class="container">

    <form action="do/login.html" method="post" class="form-signin" role="form">
        <h2 class="form-signin-heading"><i class="glyphicon glyphicon-log-in"></i> 管理员登录</h2>
        <p>${requestScope.message}</p>
        <p>${requestScope.exception.message}</p>
        <div class="form-group has-success has-feedback">
            <input name="loginAcct" type="text" class="form-control" value="jack" id="inputSuccess4" placeholder="请输入登录账号" autofocus>
            <span class="glyphicon glyphicon-user form-control-feedback"></span>
        </div>
        <div class="form-group has-success has-feedback">
            <input name="loginPswd" type="text" class="form-control" value="123123" id="inputSuccess4" placeholder="请输入登录密码" style="margin-top:10px;">
            <span class="glyphicon glyphicon-lock form-control-feedback"></span>
        </div>
<%--        <a class="btn btn-lg btn-success btn-block" href="main.html" > 登录</a>--%>
        <button class="btn btn-lg btn-success btn-block" type="submit">登录</button>
    </form>
</div>
<script src="jquery/jquery-2.1.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>

②登录成功后的页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<base href="http://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">

<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="css/font-awesome.min.css">
<link rel="stylesheet" href="css/main.css">
<style>
    .tree li {
        list-style-type: none;
        cursor: pointer;
    }

    .tree-closed {
        height: 40px;
    }

    .tree-expanded {
        height: auto;
    }
</style>

<script src="jquery/jquery-2.1.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="script/docs.min.js"></script>
<script type="text/javascript" src="layer/layer.js"></script>
<script type="text/javascript">
    $(function () {
        $(".list-group-item").click(function () {
            if ($(this).find("ul")) {
                $(this).toggleClass("tree-closed");
                if ($(this).hasClass("tree-closed")) {
                    $("ul", this).hide("fast");
                } else {
                    $("ul", this).show("fast");
                }
            }
        });
    });
</script>

</head>

<body>

    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <div><a class="navbar-brand" style="font-size:32px;" href="#">众筹平台 - 控制面板</a></div>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
            <ul class="nav navbar-nav navbar-right">
                <li style="padding-top:8px;">
                    <div class="btn-group">
                        <button type="button" class="btn btn-default btn-success dropdown-toggle"
                                data-toggle="dropdown">
                            <i class="glyphicon glyphicon-user"></i> ${sessionScope.admin.userName} <span class="caret"></span>
                        </button>
                        <ul class="dropdown-menu" role="menu">
                            <li><a href="#"><i class="glyphicon glyphicon-cog"></i> 个人设置</a></li>
                            <li><a href="#"><i class="glyphicon glyphicon-comment"></i> 消息</a></li>
                            <li class="divider"></li>
                            <li><a href="do/logout.html"><i class="glyphicon glyphicon-off"></i> 退出系统</a></li>
                        </ul>
                    </div>
                </li>
                <li style="margin-left:10px;padding-top:8px;">
                    <button type="button" class="btn btn-default btn-danger">
                        <span class="glyphicon glyphicon-question-sign"></span> 帮助
                    </button>
                </li>
            </ul>
            <form class="navbar-form navbar-right">
                <input type="text" class="form-control" placeholder="查询">
            </form>
        </div>
    </div>
</nav>

<div class="container-fluid">
    <div class="row">
      <div class="col-sm-3 col-md-2 sidebar">
    <div class="tree">
        <ul style="padding-left:0px;" class="list-group">
            <li class="list-group-item tree-closed">
                <a href="main.html"><i class="glyphicon glyphicon-dashboard"></i> 控制面板</a>
            </li>
            <li class="list-group-item tree-closed">
                        <span><i class="glyphicon glyphicon glyphicon-tasks"></i> 权限管理 <span class="badge"
                                                                                             style="float:right">3</span></span>
                <ul style="margin-top:10px;display:none;">
                    <li style="height:30px;">
                        <a href="do/admin/page.html"><i class="glyphicon glyphicon-user"></i> 用户维护</a>
                    </li>
                    <li style="height:30px;">
                        <a href="role.html"><i class="glyphicon glyphicon-king"></i> 角色维护</a>
                    </li>
                    <li style="height:30px;">
                        <a href="permission.html"><i class="glyphicon glyphicon-lock"></i> 菜单维护</a>
                    </li>
                </ul>
            </li>
            <li class="list-group-item tree-closed">
                        <span><i class="glyphicon glyphicon-ok"></i> 业务审核 <span class="badge"
                                                                                style="float:right">3</span></span>
                <ul style="margin-top:10px;display:none;">
                    <li style="height:30px;">
                        <a href="auth_cert.html"><i class="glyphicon glyphicon-check"></i> 实名认证审核</a>
                    </li>
                    <li style="height:30px;">
                        <a href="auth_adv.html"><i class="glyphicon glyphicon-check"></i> 广告审核</a>
                    </li>
                    <li style="height:30px;">
                        <a href="auth_project.html"><i class="glyphicon glyphicon-check"></i> 项目审核</a>
                    </li>
                </ul>
            </li>
            <li class="list-group-item tree-closed">
                <span><i class="glyphicon glyphicon-th-large"></i> 业务管理 <span class="badge" style="float:right">7</span></span>
                <ul style="margin-top:10px;display:none;">
                    <li style="height:30px;">
                        <a href="cert.html"><i class="glyphicon glyphicon-picture"></i> 资质维护</a>
                    </li>
                    <li style="height:30px;">
                        <a href="type.html"><i class="glyphicon glyphicon-equalizer"></i> 分类管理</a>
                    </li>
                    <li style="height:30px;">
                        <a href="process.html"><i class="glyphicon glyphicon-random"></i> 流程管理</a>
                    </li>
                    <li style="height:30px;">
                        <a href="advertisement.html"><i class="glyphicon glyphicon-hdd"></i> 广告管理</a>
                    </li>
                    <li style="height:30px;">
                        <a href="message.html"><i class="glyphicon glyphicon-comment"></i> 消息模板</a>
                    </li>
                    <li style="height:30px;">
                        <a href="project_type.html"><i class="glyphicon glyphicon-list"></i> 项目分类</a>
                    </li>
                    <li style="height:30px;">
                        <a href="tag.html"><i class="glyphicon glyphicon-tags"></i> 项目标签</a>
                    </li>
                </ul>
            </li>
            <li class="list-group-item tree-closed">
                <a href="param.html"><i class="glyphicon glyphicon-list-alt"></i> 参数管理</a>
            </li>
        </ul>
    </div>
</div>
        
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
            <h1 class="page-header">控制面板</h1>

            <div class="row placeholders">
                <div class="col-xs-6 col-sm-3 placeholder">
                    <img data-src="holder.js/200x200/auto/sky" class="img-responsive"
                         alt="Generic placeholder thumbnail">
                    <h4>Label</h4>
                    <span class="text-muted">Something else</span>
                </div>
                <div class="col-xs-6 col-sm-3 placeholder">
                    <img data-src="holder.js/200x200/auto/vine" class="img-responsive"
                         alt="Generic placeholder thumbnail">
                    <h4>Label</h4>
                    <span class="text-muted">Something else</span>
                </div>
                <div class="col-xs-6 col-sm-3 placeholder">
                    <img data-src="holder.js/200x200/auto/sky" class="img-responsive"
                         alt="Generic placeholder thumbnail">
                    <h4>Label</h4>
                    <span class="text-muted">Something else</span>
                </div>
                <div class="col-xs-6 col-sm-3 placeholder">
                    <img data-src="holder.js/200x200/auto/vine" class="img-responsive"
                         alt="Generic placeholder thumbnail">
                    <h4>Label</h4>
                    <span class="text-muted">Something else</span>
                </div>
            </div>
        </div>
    </div>
</div>

</body>
</html>


1.4后端代码

①创建当登录失败时抛出的异常类和异常映射

异常类

package com.hy.crowd.exception;

/**
 * 登录失败时抛出的异常
 */
public class LoginFailedException extends RuntimeException{
    static final long serialVersionUID = 1L;

    public LoginFailedException(String message) {
        super(message);
    }

    public LoginFailedException() {
        super();
    }
}

异常映射

    @ExceptionHandler(LoginFailedException.class)
    public ModelAndView loginFailedExceptionResolver(HttpServletRequest request, LoginFailedException e,HttpServletResponse response) throws IOException {

        return exceptionResolver(request,response,e,"admin-login");
    }

②service

接口

package com.hy.crowd.service.api;

import com.github.pagehelper.PageInfo;
import com.hy.crowd.entity.Admin;

public interface AdminService {
    Admin doLogin(String loginAcct, String loginPswd);
}

实现类

package com.hy.crowd.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hy.crowd.constant.CrowdConstant;
import com.hy.crowd.entity.Admin;
import com.hy.crowd.entity.AdminExample;
import com.hy.crowd.exception.LoginAcctAlreadyInUseException;
import com.hy.crowd.exception.LoginFailedException;
import com.hy.crowd.mapper.AdminMapper;
import com.hy.crowd.service.api.AdminService;
import com.hy.crowd.utils.CrowdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author hy
 * @create 2022-08-17 14:33
 * @Description
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;


    @Override
    public Admin doLogin(String loginAcct, String loginPswd) {

        // 1.根据用户名找到这个用户
        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria().andLoginAcctEqualTo(loginAcct);

        List<Admin> admins = adminMapper.selectByExample(adminExample);

        // 判断找出的列表中是否有数据
        if(admins == null || admins.size() != 1){
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_ACCT_FAILED);
        }

        Admin admin = admins.get(0);

        // 2.将表单密码进行加密
        String encode = CrowdUtils.encode(loginPswd);

        // 3.比较密码
        if (Objects.equals(encode,admin.getLoginPswd())){
            // 3.1如果相等那么就返回admin对象
            return admin;
        }
        return null;
    }
}

③handler

package com.hy.crowd.mvc.handler;

import com.github.pagehelper.PageInfo;
import com.hy.crowd.constant.CrowdConstant;
import com.hy.crowd.entity.Admin;
import com.hy.crowd.service.api.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class AdminHandler {

    @Autowired
    private AdminService adminService;

    @RequestMapping("/do/login.html")
    public String doLogin(@RequestParam("loginAcct") String loginAcct,
                          @RequestParam("loginPswd") String loginPswd,
                          ModelMap modelMap,
                          HttpSession session){

        Admin admin = adminService.doLogin(loginAcct,loginPswd);

        if(admin == null){
            modelMap.addAttribute(CrowdConstant.ATTR_SYSTEM_MESSAGE,CrowdConstant.MESSAGE_LOGIN_FAILD);
            return "admin-login";
        }

        // 登录成功则把admin对象放入到session域中
        session.setAttribute(CrowdConstant.ATTR_ADMIN_NAME,admin);

		// 重定向到主页
        return "redirect:/to/admin/main.html";
    }
}

④在mvc的配置文件中声明页面的映射,方便重定向

<mvc:view-controller path="/to/admin/main.html" view-name="admin-main"></mvc:view-controller>

⑤设置退出登录

    @RequestMapping("/do/logout.html")
    public String doLogout(HttpSession session){

        session.invalidate();

        return "admin-login";
    }

1.5抽取出公共页面

在这里插入图片描述

①include-head.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<base href="http://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">

<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="css/font-awesome.min.css">
<link rel="stylesheet" href="css/main.css">
<style>
    .tree li {
        list-style-type: none;
        cursor: pointer;
    }

    .tree-closed {
        height: 40px;
    }

    .tree-expanded {
        height: auto;
    }
</style>

<script src="jquery/jquery-2.1.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="script/docs.min.js"></script>
<script type="text/javascript" src="layer/layer.js"></script>
<script type="text/javascript">
    $(function () {
        $(".list-group-item").click(function () {
            if ($(this).find("ul")) {
                $(this).toggleClass("tree-closed");
                if ($(this).hasClass("tree-closed")) {
                    $("ul", this).hide("fast");
                } else {
                    $("ul", this).show("fast");
                }
            }
        });
    });
</script>

②include-nav.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <div><a class="navbar-brand" style="font-size:32px;" href="#">众筹平台 - 控制面板</a></div>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
            <ul class="nav navbar-nav navbar-right">
                <li style="padding-top:8px;">
                    <div class="btn-group">
                        <button type="button" class="btn btn-default btn-success dropdown-toggle"
                                data-toggle="dropdown">
                            <i class="glyphicon glyphicon-user"></i> ${sessionScope.admin.userName} <span class="caret"></span>
                        </button>
                        <ul class="dropdown-menu" role="menu">
                            <li><a href="#"><i class="glyphicon glyphicon-cog"></i> 个人设置</a></li>
                            <li><a href="#"><i class="glyphicon glyphicon-comment"></i> 消息</a></li>
                            <li class="divider"></li>
                            <li><a href="do/logout.html"><i class="glyphicon glyphicon-off"></i> 退出系统</a></li>
                        </ul>
                    </div>
                </li>
                <li style="margin-left:10px;padding-top:8px;">
                    <button type="button" class="btn btn-default btn-danger">
                        <span class="glyphicon glyphicon-question-sign"></span> 帮助
                    </button>
                </li>
            </ul>
            <form class="navbar-form navbar-right">
                <input type="text" class="form-control" placeholder="查询">
            </form>
        </div>
    </div>
</nav>

③include-sidebar

<%--
  Created by IntelliJ IDEA.
  User: hy
  Date: 2022/8/17
  Time: 14:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<div class="col-sm-3 col-md-2 sidebar">
    <div class="tree">
        <ul style="padding-left:0px;" class="list-group">
            <li class="list-group-item tree-closed">
                <a href="main.html"><i class="glyphicon glyphicon-dashboard"></i> 控制面板</a>
            </li>
            <li class="list-group-item tree-closed">
                        <span><i class="glyphicon glyphicon glyphicon-tasks"></i> 权限管理 <span class="badge"
                                                                                             style="float:right">3</span></span>
                <ul style="margin-top:10px;display:none;">
                    <li style="height:30px;">
                        <a href="do/admin/page.html"><i class="glyphicon glyphicon-user"></i> 用户维护</a>
                    </li>
                    <li style="height:30px;">
                        <a href="role.html"><i class="glyphicon glyphicon-king"></i> 角色维护</a>
                    </li>
                    <li style="height:30px;">
                        <a href="permission.html"><i class="glyphicon glyphicon-lock"></i> 菜单维护</a>
                    </li>
                </ul>
            </li>
            <li class="list-group-item tree-closed">
                        <span><i class="glyphicon glyphicon-ok"></i> 业务审核 <span class="badge"
                                                                                style="float:right">3</span></span>
                <ul style="margin-top:10px;display:none;">
                    <li style="height:30px;">
                        <a href="auth_cert.html"><i class="glyphicon glyphicon-check"></i> 实名认证审核</a>
                    </li>
                    <li style="height:30px;">
                        <a href="auth_adv.html"><i class="glyphicon glyphicon-check"></i> 广告审核</a>
                    </li>
                    <li style="height:30px;">
                        <a href="auth_project.html"><i class="glyphicon glyphicon-check"></i> 项目审核</a>
                    </li>
                </ul>
            </li>
            <li class="list-group-item tree-closed">
                <span><i class="glyphicon glyphicon-th-large"></i> 业务管理 <span class="badge" style="float:right">7</span></span>
                <ul style="margin-top:10px;display:none;">
                    <li style="height:30px;">
                        <a href="cert.html"><i class="glyphicon glyphicon-picture"></i> 资质维护</a>
                    </li>
                    <li style="height:30px;">
                        <a href="type.html"><i class="glyphicon glyphicon-equalizer"></i> 分类管理</a>
                    </li>
                    <li style="height:30px;">
                        <a href="process.html"><i class="glyphicon glyphicon-random"></i> 流程管理</a>
                    </li>
                    <li style="height:30px;">
                        <a href="advertisement.html"><i class="glyphicon glyphicon-hdd"></i> 广告管理</a>
                    </li>
                    <li style="height:30px;">
                        <a href="message.html"><i class="glyphicon glyphicon-comment"></i> 消息模板</a>
                    </li>
                    <li style="height:30px;">
                        <a href="project_type.html"><i class="glyphicon glyphicon-list"></i> 项目分类</a>
                    </li>
                    <li style="height:30px;">
                        <a href="tag.html"><i class="glyphicon glyphicon-tags"></i> 项目标签</a>
                    </li>
                </ul>
            </li>
            <li class="list-group-item tree-closed">
                <a href="param.html"><i class="glyphicon glyphicon-list-alt"></i> 参数管理</a>
            </li>
        </ul>
    </div>
</div>

④抽取完页面的main页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <%@include file="/WEB-INF/include/include-head.jsp"%>
</head>

<body>

    <%@include file="/WEB-INF/include/include-nav.jsp"%>
<div class="container-fluid">
    <div class="row">
        <%@include file="/WEB-INF/include/include-sidebar.jsp"%>
        
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
            <h1 class="page-header">控制面板</h1>

            <div class="row placeholders">
                <div class="col-xs-6 col-sm-3 placeholder">
                    <img data-src="holder.js/200x200/auto/sky" class="img-responsive"
                         alt="Generic placeholder thumbnail">
                    <h4>Label</h4>
                    <span class="text-muted">Something else</span>
                </div>
                <div class="col-xs-6 col-sm-3 placeholder">
                    <img data-src="holder.js/200x200/auto/vine" class="img-responsive"
                         alt="Generic placeholder thumbnail">
                    <h4>Label</h4>
                    <span class="text-muted">Something else</span>
                </div>
                <div class="col-xs-6 col-sm-3 placeholder">
                    <img data-src="holder.js/200x200/auto/sky" class="img-responsive"
                         alt="Generic placeholder thumbnail">
                    <h4>Label</h4>
                    <span class="text-muted">Something else</span>
                </div>
                <div class="col-xs-6 col-sm-3 placeholder">
                    <img data-src="holder.js/200x200/auto/vine" class="img-responsive"
                         alt="Generic placeholder thumbnail">
                    <h4>Label</h4>
                    <span class="text-muted">Something else</span>
                </div>
            </div>
        </div>
    </div>
</div>

</body>
</html>

⑤模板文件

<%--
  Created by IntelliJ IDEA.
  User: hy
  Date: 2022/8/17
  Time: 14:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <%@include file="/WEB-INF/include/include-head.jsp"%>
</head>

<body>

    <%@include file="/WEB-INF/include/include-nav.jsp"%>
<div class="container-fluid">
    <div class="row">
        <%@include file="/WEB-INF/include/include-sidebar.jsp"%>
        

    </div>
</div>

</body>
</html>

1.6登录状态检查(拦截器)

①思路

在这里插入图片描述

②异常类 AccessForbiddenException

package com.hy.crowd.exception;

public class AccessForbiddenException extends RuntimeException{
    static final long serialVersionUID = 1L;

    public AccessForbiddenException() {
        super();
    }

    public AccessForbiddenException(String message) {
        super(message);
    }
}

③异常解析方式

注:这个异常只能使用xml的方式进行异常解析才会生效,亲测在使用注解的方式不会生效

    <bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="com.hy.crowd.exception.AccessForbiddenException">admin-login</prop>
            </props>
        </property>
    </bean>

④过滤器 CrowdInterceptor

package com.hy.crowd.mvc.config;

import com.hy.crowd.constant.CrowdConstant;
import com.hy.crowd.entity.Admin;
import com.hy.crowd.exception.AccessForbiddenException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CrowdInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.从session域中获取admin对象
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute(CrowdConstant.ATTR_ADMIN_NAME);

        // 2.判断对象是否为null
        if(admin == null){
            // 为null则直接抛出异常
            throw new AccessForbiddenException(CrowdConstant.MESSAGE_ACCESS_FORBIDDEN);
        }

        // 3.对象存在则直接放行
        return true;
    }
}

⑤在配置文件中声明过滤器

<!--  注:拦截器抛出的异常只有在配置文件中才能捕获到,而在使用注解的方式捕获不到  -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--   将全部路径设置为不可访问         -->
            <mvc:mapping path="/**"/>
            <!--   放行的路径     -->
            <mvc:exclude-mapping path="/"/>
            <mvc:exclude-mapping path="/to/login.html"/>
            <mvc:exclude-mapping path="/do/login.html"/>
            <!--  配置拦截器类          -->
            <bean class="com.hy.crowd.mvc.config.CrowdInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

2.用户模块

2.1分页显示数据

①思路

在这里插入图片描述

②前端页面修改

include-sidebar.jsp

 <a href="do/admin/page.html"><i class="glyphicon glyphicon-user"></i> 用户维护</a>

③添加依赖

common的pom.xml

        <!-- MyBatis 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
        </dependency>

④在mybatis的配置文件中添加插件

mybatis-config.xml

    <!--  引入PageHelper这个插件  -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
                <!--   开启页码的自动修正         -->
            <property name="reasonable" value="true"/>
        </plugin>
    </plugins>

⑤在mapper中添加方法

AdminMapper.xml

<!--  List<Admin> selectAdminByKeyword(String keyword);-->
  <select id="selectAdminByKeyword" resultMap="BaseResultMap">
    select id, login_acct, login_pswd, user_name, email, create_time
    from t_admin
    where login_acct like concat('%',#{keyword},'%')
    or user_name like concat('%',#{keyword},'%')
    or email like concat('%',#{keyword},'%')
  </select>

⑥AdminService方法

    @Override
    public PageInfo<Admin> getPageInfo(Integer pageNum, Integer pageSize, String keyword) {
        PageHelper.startPage(pageNum,pageSize);

        List<Admin> admins = adminMapper.selectAdminByKeyword(keyword);

        PageInfo<Admin> pageInfo = new PageInfo<>(admins);
        return pageInfo;
    }

⑦AdminHandler方法

    @RequestMapping("/do/admin/page.html")
    public String getPageInfo(
            @RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
            @RequestParam(value = "pageSize",defaultValue = "5")Integer pageSize,
            @RequestParam(value = "keyword",defaultValue = "")String keyword,
            ModelMap modelMap){

        PageInfo<Admin> pageInfo = adminService.getPageInfo(pageNum,pageSize,keyword);

        modelMap.addAttribute(CrowdConstant.ATTR_PAGE_NAME,pageInfo);


     	return "admin/admin-page";
    }

⑧添加分页页面

添加JSTL标签库

 <!-- JSTL 标签库 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <%@include file="/WEB-INF/include/include-head.jsp" %>
  
</head>

<body>

<%@include file="/WEB-INF/include/include-nav.jsp" %>
<div class="container-fluid">
    <div class="row">
        <%@include file="/WEB-INF/include/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 method="post" action="do/admin/page.html" 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 value="${param.keyword}" name="keyword" class="form-control has-success" type="text" placeholder="请输入查询条件">
                            </div>
                        </div>
                        <button type="submit" 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;"--%>
<%--                            οnclick="window.location.href='add.html'"><i class="glyphicon glyphicon-plus"></i> 新增--%>
<%--                    </button>--%>
                    <a class="btn btn-primary" style="float:right;" href="to/admin/add.html">
                        <i class="glyphicon glyphicon-plus"></i> 新增
                    </a>
                    <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>名称</th>
                                <th>邮箱地址</th>
                                <th width="100">操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <c:if test="${empty pageInfo}">数据为空无法访问</c:if>
                            <c:if test="${not empty pageInfo}">
                                <c:forEach items="${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>
                                            <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>
                                </c:forEach>
                            </c:if>

                            </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>

⑨实现分页条功能(调用Pagination)

详情请看另一篇文章:https://editor.csdn.net/md/?articleId=126393127

⑩实现关键词查询

前端页面

 <form method="post" action="do/admin/page.html" 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 value="${param.keyword}" name="keyword" class="form-control has-success" 		 type="text" placeholder="请输入查询条件">
                            </div>
                        </div>
                        <button type="submit" class="btn btn-warning"><i class="glyphicon glyphicon-search"></i> 查询
                        </button>
                    </form>

2.2实现添加功能

①思路

在这里插入图片描述

②修改新增按钮

<%--                    <button type="button" class="btn btn-primary" style="float:right;"--%>
<%--                            οnclick="window.location.href='add.html'"><i class="glyphicon glyphicon-plus"></i> 新增--%>
<%--                    </button>--%>
                    <a class="btn btn-primary" style="float:right;" href="to/admin/add.html">
                        <i class="glyphicon glyphicon-plus"></i> 新增

③增加一个添加用户的表单

admin-add.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="zh-CN">
<head>
    <%@include file="/WEB-INF/include/include-head.jsp" %>
</head>

<body>

<%@include file="/WEB-INF/include/include-nav.jsp" %>
<div class="container-fluid">
    <div class="row">
        <%@include file="/WEB-INF/include/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="#">首页</a></li>
                <li><a href="#">数据列表</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="do/admin/save.html" method="post" role="form">
                        <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="loginPswd" 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 name="email" type="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>

④添加用户异常时抛出的异常类

package com.hy.crowd.exception;

public class LoginAcctAlreadyInUseException extends RuntimeException{

    public LoginAcctAlreadyInUseException() {
        super();
    }

    public LoginAcctAlreadyInUseException(String message) {
        super(message);
    }
}

异常解析

    @ExceptionHandler(LoginAcctAlreadyInUseException.class)
    public ModelAndView loginAcctAlreadyInUseExceptionResolver(HttpServletRequest request, LoginAcctAlreadyInUseException e,HttpServletResponse response) throws IOException {
		
        return exceptionResolver(request,response,e,"system-error");
    }

⑤将数据库中的login_acct字段设置为唯一索引

ALTER TABLE t_admin ADD UNIQUE(login_acct)
show index from t_admin

⑥AdminService方法

@Override
    public void saveAdmin(Admin admin) {
        // 1.取出密码,加密后再放回
        String loginPswd = admin.getLoginPswd();
        String encode = CrowdUtils.encode(loginPswd);
        admin.setLoginPswd(encode);

        // 2.设置创建时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String createTime = sdf.format(date);
        admin.setCreateTime(createTime);

        // 3.使用mapper添加
        try {
            adminMapper.insertSelective(admin);
        } catch (Exception e) {
            // 检测当前捕获的异常对象,如果是 DuplicateKeyException 类型说明是账号重复导致的
            if(e instanceof DuplicateKeyException){
                throw new LoginAcctAlreadyInUseException(CrowdConstant.MESSAGE_LOGIN_ALREAD);
            }
        }
    }

⑦AdminHandler方法

    @RequestMapping("/do/admin/save.html")
    public String saveAdmin(Admin admin){

        adminService.saveAdmin(admin);

        return "redirect:/do/admin/page.html?pageNum="+Integer.MAX_VALUE;
    }

2.3实现修改的功能

①思路

在这里插入图片描述

②修改携带id值跳转的链接按钮

<%--<button type="button" class="btn btn-primary btn-xs"><i--%>
<%--class=" glyphicon glyphicon-pencil"></i></button>--%>
<a  class="btn btn-primary btn-xs" href="to/admin/update.html?id=${admin.id}&pageNum=${pageInfo.pageNum}&keyword=${param.keyword}">
<i class=" glyphicon glyphicon-pencil"></i>
</a>

③后台通过id获取Admin的方法

handler

    @RequestMapping("/to/admin/update.html")
    public String toUpdate(
            @RequestParam("id")Integer id,
            @RequestParam("pageNum")Integer pageNum,
            @RequestParam("keyword")String keyword,
            ModelMap modelMap
    ){

        Admin admin = adminService.getAdminById(id);

        modelMap.addAttribute(CrowdConstant.ATTR_ADMIN_NAME,admin);

        return "admin/admin-update";
    }

Service

    @Override
    public Admin getAdminById(Integer id) {
        return adminMapper.selectByPrimaryKey(id);
    }

③修改页面admin-upadte.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="zh-CN">
<head>
    <%@include file="/WEB-INF/include/include-head.jsp" %>
</head>

<body>

<%@include file="/WEB-INF/include/include-nav.jsp" %>
<div class="container-fluid">
    <div class="row">
        <%@include file="/WEB-INF/include/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="#">首页</a></li>
                <li><a href="#">数据列表</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 role="form" action="do/admin/update.html" method="post">
                        <input type="hidden" name="id" value="${param.id}">
                        <input type="hidden" name="pageNum" value="${ param.pageNum}">
                        <input type="hidden" name="keyword" value="${ param.keyword}">
                        <div class="form-group">
                            <label for="exampleInputPassword1">登陆账号</label>
                            <input name="loginAcct" type="text" class="form-control" id="exampleInputPassword1" value="${admin.loginAcct}">
                        </div>
                        <div class="form-group">
                            <label for="exampleInputPassword1">用户名称</label>
                            <input name="userName" type="text" class="form-control" id="exampleInputPassword1" value="${admin.userName}">
                        </div>
                        <div class="form-group">
                            <label for="exampleInputEmail1">邮箱地址</label>
                            <input name="email" type="email" class="form-control" id="exampleInputEmail1" value="${admin.email}">
                            <p class="help-block label label-warning">请输入合法的邮箱地址, 格式为: xxxx@xxxx.com</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>
    </div>
</div>

</body>
</html>

④提交修改表单,完成修改功能的后台方法

AdminHandler

    @RequestMapping("/do/admin/update.html")
    public String Update(
            Admin admin,
            @RequestParam("pageNum")Integer pageNum,
            @RequestParam("keyword")String keyword){

        adminService.update(admin);


        return "redirect:/do/admin/page.html?pageNum="+pageNum+"&keyword"+keyword;
    }

AdminService

    @Override
    public void update(Admin admin) {
        try {
        	// 检查在修改时是否会出现用户名重复问题,如果出现就报错,跳转到system-error页面
            adminMapper.updateByPrimaryKeySelective(admin);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException){
                throw new LoginAcctAlreadyInUseException(CrowdConstant.MESSAGE_LOGIN_ALREAD);
            }
        }
    }

2.4实现删的功能

①思路

在这里插入图片描述

②前端跳转链接

 <a  class="btn btn-danger btn-xs" href="do/admin/delete.html?id=${admin.id}&pageNum=${pageInfo.pageNum}&keyword=${param.keyword}">
	<i class=" glyphicon glyphicon-remove"></i>
 </a>

③AdminHandler

    @RequestMapping("/do/admin/delete.html")
    public String delete(
            @RequestParam("id")Integer id,
            @RequestParam("pageNum")Integer pageNum,
            @RequestParam("keyword")String keyword
    ){
        adminService.deleteAdminById(id);

        return "redirect:/do/admin/page.html?pageNum="+pageNum+"&keyword="+keyword;
    }

④AdminService

    @Override
    public void deleteAdminById(Integer id) {

        adminMapper.deleteByPrimaryKey(id);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值