尚筹网项目第二天 2020-03-23 11:37:10

本文档大多来源于尚硅谷【封捷】老师所讲的尚筹网项目:

尚硅谷尚筹网项目视频教程
下载链接:https://pan.baidu.com/s/1WOLG7b4yHkQfSMu3fMsOBA 
提取码:s5gw

后台登陆功能:

1、以常量代替字符串

 好处:防止字写错

package com.atguigu.crowd.constant;


public class CrowdConstant {
    public static final String LOGIN_ATTR_ERROR_MESSAGE = "用户名或密码错误,请重新输入。";
    public static final String LOGIN_ADMIN_MESSAGE = "adminMessage";
    public static final String SYSTEM_ADMIN_DATA_MESSAGE = "数据库存在用户名相同的多条数据,请检查数据";
    public static final String MESSAGE_STRING_INVALIDATE = "传入的数据不能为null";
    public static final String VALIDATE_ADMIN_MESSAGE_NOTEXISTS = "请重新登陆本系统";
    public static String Admin_PAGE_MESSAGE = "adminPage";
}

 2、引入登陆页面

<%--
Created by IntelliJ IDEA.
User: 25017
Date: 2020/3/23
Time: 12:03
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<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">
<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="admin/go/login.html" method="post" class="form-signin" role="form">
<h2 class="form-signin-heading"><i class="glyphicon glyphicon-log-in"></i> 用户登录</h2>
<p>${requestScope.exception.message }</p>
<div class="form-group has-success has-feedback">
<input type="text" class="form-control" name="loginAcct" id="inputSuccess4" placeholder="请输入登录账号" autofocus>
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-success has-feedback">
<input type="text" class="form-control" name="userPswd" id="inputSuccess4" placeholder="请输入登录密码" style="margin-top:10px;">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="checkbox" style="text-align:right;"><a href="reg.html">我要注册</a></div>
<button type="submit" class="btn btn-lg btn-success btn-block">登录</button>
</form>
</div>
<script src="jquery/jquery-2.1.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>

 

去往登陆页面的handler

@Autowired
    private AdmainService admainService;

    @RequestMapping("/admin/login.html")
    public String goToAdminLoginPage(){
        return "login";
    }

 

3、登陆功能的原理

自定义登陆失败异常类:

package com.atguigu.crowd.exception;

public class LoginFailedException extends RuntimeException {
    public LoginFailedException() {
        super();
    }

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

    public LoginFailedException(String message, Throwable cause) {
        super(message, cause);
    }

    public LoginFailedException(Throwable cause) {
        super(cause);
    }

    protected LoginFailedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

处理登陆失败异常:

 @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);
    }

handler:

@RequestMapping("/admin/go/login.html")
    public String doLogin(
            @RequestParam("loginAcct") String loginAcct,
            @RequestParam("userPswd") String userPswd,
            HttpSession session){
        //1、根据用户名和密码查询登陆用户
        Admin admin = admainService.getAdminByLoginAcct(loginAcct,userPswd);
        //2、查询不到,直接抛出异常
        if(admin == null){
            throw new LoginFailedException(CrowdConstant.LOGIN_ATTR_ERROR_MESSAGE);
        }
        //3、能查询到,将用户信息放入session中
        session.setAttribute(CrowdConstant.LOGIN_ADMIN_MESSAGE,admin);
        //4、重定向到主页面
        return "redirect:/admin/main.html";
    }

 

service:

@Override
    public Admin getAdminByLoginAcct(String loginAcct, String userPswd) {
        // mybatis QBC查询
        // 1、根据用户名查询用户信息
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        criteria.andLoginAcctEqualTo(loginAcct);
        List<Admin> admins = adminMapper.selectByExample(example);
        // 2、查不到:直接返回null
        if(admins == null || admins.size() == 0){
            throw new LoginFailedException(CrowdConstant.LOGIN_ATTR_ERROR_MESSAGE);
        }
        
        if(admins.size() > 1){
            throw new RuntimeException(CrowdConstant.SYSTEM_ADMIN_DATA_MESSAGE);
        }

        // 3、能查到
        Admin admin = admins.get(0);
        // 4、获取查询到的密码
        String userPswdDB = admin.getUserPswd();

        // 5、将传入的密码进行md5加密
        String userPswdMD5 = CrowdUtil.md5(userPswd);
        // 6、比较传入的密码和数据库查询到的密码
        if(!Objects.equals(userPswdDB,userPswdMD5)){
            throw new LoginFailedException(CrowdConstant.LOGIN_ATTR_ERROR_MESSAGE);
        }

        // 8、一致,返回用户对象
        return admin;
    }

mapper使用mybatis逆向工程生成的:

md5加密:

package com.atguigu.crowd.util;

import com.atguigu.crowd.constant.CrowdConstant;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class CrowdUtil {

    /**
     * 对明文字符串进行MD5加密
     * @param source 传入的明文字符串
     * @return 加密结果
     */
    public static String md5(String source) {

        // 1.判断source是否有效
        if(source == null || source.length() == 0) {

            // 2.如果不是有效的字符串抛出异常
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }

        try {
            // 3.获取MessageDigest对象
            String algorithm = "md5";

            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);

            // 4.获取明文字符串对应的字节数组
            byte[] input = source.getBytes();

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

            // 6.创建BigInteger对象
            int signum = 1;
            BigInteger bigInteger = new BigInteger(signum, output);

            // 7.按照16进制将bigInteger的值转换为字符串
            int radix = 16;
            String encoded = bigInteger.toString(radix).toUpperCase();

            return encoded;

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

        return null;
    }
    
    /**
     * 判断当前请求是否为Ajax请求
     * @param request 请求对象
     * @return
     *         true:当前请求是Ajax请求
     *         false:当前请求不是Ajax请求
     */
    public static boolean judgeRequestType(HttpServletRequest request) {
        
        // 1.获取请求消息头
        String acceptHeader = request.getHeader("Accept");
        String xRequestHeader = request.getHeader("X-Requested-With");
        
        // 2.判断
        return (acceptHeader != null && acceptHeader.contains("application/json"))
                
                ||
                
                (xRequestHeader != null && xRequestHeader.equals("XMLHttpRequest"));
    }

}

 

4、退出登陆功能

页面:

<li><a href="admin/logout.html"><i class="glyphicon glyphicon-off"></i> 退出系统</a></li>

 

代码:

@RequestMapping("/admin/logout.html")
    public String doLogout(HttpSession session){
        session.invalidate();
        return "redirect:/admin/login.html";
    }

 

5、登陆状态的检查---springmvc的拦截器

自定义登陆检查的异常:

package com.atguigu.crowd.exception;

public class AccessForbiddenException extends RuntimeException {
    public AccessForbiddenException() {
        super();
    }

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

    public AccessForbiddenException(String message, Throwable cause) {
        super(message, cause);
    }

    public AccessForbiddenException(Throwable cause) {
        super(cause);
    }

    protected AccessForbiddenException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

 

拦截器的代码:

package com.atguigu.crowd.mvc.interceptor;

import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.entity.Admin;
import com.atguigu.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 LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 1.通过 request 对象获取 Session 对象
        HttpSession session = request.getSession();
        // 2.尝试从 Session 域中获取 Admin 对象
        Admin adminMessage = (Admin)session.getAttribute(CrowdConstant.LOGIN_ADMIN_MESSAGE);
        // 3.判断 admin 对象是否为空
        if(adminMessage == null){
            // 4、抛出AccessForbiddenException异常
            throw new AccessForbiddenException(CrowdConstant.VALIDATE_ADMIN_MESSAGE_NOTEXISTS);
        }

        // 5.如果 Admin 对象不为 null,则返回 true 放行
        return true;
    }
}

在springmvc的配置文件配置拦截器:

<!-- 拦截器的配置 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!-- mvc:mapping 配置要拦截的资源 -->
            <!-- /*对应一层路径,比如:/aaa -->
            <!-- /**对应多层路径,比如:/aaa/bbb 或/aaa/bbb/ccc 或/aaa/bbb/ccc/ddd -->
            <mvc:mapping path="/**"/>
            <!-- mvc:exclude-mapping 配置不拦截的资源 -->
            <!-- 去登陆页面 -->
            <mvc:exclude-mapping path="/admin/login.html"/>
            <!-- 执行登陆请求 -->
            <mvc:exclude-mapping path="/admin/go/login.html"/>
            <!-- 退出登陆 -->
            <mvc:exclude-mapping path="/admin/logout.html"/> <!-- 配置拦截器类 -->
            <bean class="com.atguigu.crowd.mvc.interceptor.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

 

完善拦截器的异常映射:【只有基于xml的异常配置才能使拦截器中抛出的异常被处理】

<!-- 配置基于 XML 的异常映射 -->
    <bean id="simpleMappingExceptionResolver"
          class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <!-- 指定异常类型和逻辑视图名称的对应关系 -->
        <property name="exceptionMappings">
            <props>
                <!-- key 属性指定异常类型(全类名) -->
                <!-- 文本标签体中指定异常对应的逻辑视图名称 -->
                <prop key="java.lang.NullPointerException">system-error</prop>
                <!-- 完善配套的异常映射 -->
                <prop key="com.atguigu.crowd.exception.AccessForbiddenException">admin-login</prop>
            </props>
        </property>
        <!-- 使用 exceptionAttribute 可以修改异常对象存入请求域时使用的属性名 -->
        <!-- <property name="exceptionAttribute"></property> -->
    </bean>

 

异常处理:

@ExceptionHandler(value = AccessForbiddenException.class)
    public ModelAndView resolveAccessForbiddenExceptionException(
            LoginFailedException exception,
            HttpServletRequest request,
            HttpServletResponse response ) throws IOException {
        String viewName = "admin-login";
        return commonResolve(viewName, exception, request, response);
    }

 

6、公共页面的抽取

注意:主页面和其他被引入的页面头部必须相同:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

主页面:

<%--
  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">
            <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>

include-head:

<%--
  Created by IntelliJ IDEA.
  User: 25017
  Date: 2020/3/23
  Time: 14:26
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<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 type="text/javascript" src="jquery/jquery-2.1.1.min.js"></script>
    <script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
    <script type="text/javascript" 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>
    <title>尚筹网</title>
</head>

 

include-nav:

<%--
  Created by IntelliJ IDEA.
  User: 25017
  Date: 2020/3/23
  Time: 14:33
  To change this template use File | Settings | File Templates.
--%>
<%@ 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" aria-expanded="false">
                            <i class="glyphicon glyphicon-user"></i> zs <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="admin/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: 25017
  Date: 2020/3/23
  Time: 14:35
  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="user.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>

 

本后台系统的页面模板:

<%--
  Created by IntelliJ IDEA.
  User: 25017
  Date: 2020/3/23
  Time: 20:25
  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">
      <!-- 各个页面独自的部分 -->
        </div>
    </div>
</div>

</body>
</html>

 

管理员信息的分页显示

使用的技术:

①concat函数的使用

CONCAT("%",#{keyword},"%")

②pagehelper的使用

引入依赖

在 SqlSessionFactoryBean 中配置 PageHelper

在 Java 代码中使用

PageHelper.startPage(pageNum, pageSize);

PageInfo<Admin> pageInfo = new PageInfo(adminList );

③使用jquery的插件pagenation

思路:

pom依赖:

<!-- pageHelper依赖【mybatis分页】 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
        </dependency>

mybatis与spring整合的配置文件:【配置pageHelper插件】

<!-- 配置 SqlSessionFactoryBean -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 装配数据源 -->
        <property name="dataSource" ref="dataSource"/> <!-- 指定 MyBatis 全局配置文件位置 -->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/> <!-- 指定 Mapper 配置文件位置 -->
        <property name="mapperLocations" value="classpath:mybatis/mapper/*Mapper.xml"/>
        <!-- 配置 MyBatis 的插件 -->
        <property name="plugins">
            <array>
                <!-- 配置 PageHelper -->
                <bean class="com.github.pagehelper.PageHelper">
                    <!-- 配置相关属性 -->
                    <property name="properties">
                        <props>
                            <!-- 配置数据库方言,告诉 PageHelper 当前使用的具体数据库, -->
                            <!-- 让 PageHelper 可以根据当前数据库生成对应的分页 SQL 语 句 -->
                            <prop key="dialect">mysql</prop>
                            <!-- 配置页码的合理化修正 -->
                            <!-- 让 PageHelper 自动把浏览器传来的 PageNum 修正到 0~总页 数范围 -->
                            <prop key="reasonable">true</prop>
                        </props>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

mapper.xml

<select id="selectAdminListByKeyword" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from t_admin
    where
    login_acct like CONCAT("%",#{keyword},"%") or
    user_name like CONCAT("%",#{keyword},"%") or
    email like CONCAT("%",#{keyword},"%")
  </select>

mapper接口:

List<Admin> selectAdminListByKeyword(String keyword);

service具体实现:

@Override
    public PageInfo<Admin> getAdminPage(String keyword, Integer pageNum, Integer pageSize) {

        // 1.开启分页功能
        PageHelper.startPage(pageNum,pageSize);

        // 2.查询 Admin 数据
        List<Admin> adminList = adminMapper.selectAdminListByKeyword(keyword);

        // 3.为了方便页面使用将 adminList 封装为 PageInfo
        PageInfo<Admin> pageInfo = new PageInfo<>(adminList);

        return pageInfo;
    }

 

handler具体实现:

@RequestMapping("/admin/page.html")
    public String getAdminPage(
            // 注意:页面上有可能不提供关键词,要进行适配
            // 在@RequestParam注解中设置defaultValue属性为空字符串表示浏览器不提 供关键词时,keyword 变量赋值为空字符串
            @RequestParam(value = "keyword",defaultValue = "")String keyword,
            // 浏览器未提供 pageNum 时,默认前往第一页
            @RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
            // 浏览器未提供 pageSize 时,默认每页显示 5 条记录
            @RequestParam(value = "pageSize",defaultValue = "5")Integer pageSize,
            ModelMap modelMap){
        // 查询得到分页数据
        PageInfo<Admin> adminPage = admainService.getAdminPage(keyword, pageNum, pageSize);

        // 将分页数据存入模型

        modelMap.addAttribute(CrowdConstant.Admin_PAGE_MESSAGE,adminPage);

        return "admin-page";
    }

 

前台页面部分:

需要加入的内容:

页面代码:

<%--
  Created by IntelliJ IDEA.
  User: 25017
  Date: 2020/3/23
  Time: 15:49
  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" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="C" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html lang="UTF-8">
<%@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 type="text/javascript">
    $(function(){
        // 调用专门的函数初始化分页导航条
        initPagination();
    });

    // 声明一个函数用于初始化 Pagination
    function initPagination(){
        // 获取分页数据中的总记录数
        var totalRecord = ${requestScope.adminPage.total};

        // 声明 Pagination 设置属性的 JSON 对象
        var properties = {
            num_edge_entries: 3, // 边缘页数
            num_display_entries: 5, // 主体页数
            callback: pageSelectCallback, // 用户点击“翻页”按钮之后 执行翻页操作的回调函数
            current_page: ${requestScope.adminPage.pageNum-1}, // 当前页,pageNum 从 1 开始, 必须-1 后才可以赋值
            prev_text: "上一页",
            next_text: "下一页",
            items_per_page:${requestScope.adminPage.pageSize} // 每页显示 多少 项
        };

        // 调用分页导航条对应的 jQuery 对象的 pagination()方法生成导航条
        $("#Pagination").pagination(totalRecord, properties);

    }

    // 翻页过程中执行的回调函数
    // 点击“上一页”、“下一页”或“数字页码”都会触发翻页动作,从而导致当前函数被调 用
    // pageIndex 是用户在页面上点击的页码数值
    function  pageSelectCallback(pageIndex,JQuery) {
        // pageIndex 是当前页页码的索引,相对于 pageNum 来说,pageIndex 比 pageNum 小 1
        var pageNum = pageIndex + 1;

        // 执行页面跳转也就是实现“翻页”
        window.location.href = "admin/page.html?pageNum="+pageNum+"&keyword=${param.keyword}";

        // 取消当前超链接的默认行为
        return false;
    }

</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 action="admin/page.html" method="post" 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" name="keyword" 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;" 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">#</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 requestScope.adminPage.list}">
                                <tr>
                                    <td colspan="6" align="center">抱歉!没有查询到您要的数据!</td>
                                </tr>
                            </C:if>
                            <C:if test="${!empty requestScope.adminPage.list}">
                                <c:forEach items="${requestScope.adminPage.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>

 

 需要将jquery.pagination.js文件调用回调函数那行去掉,否则会死循环,CPU贼高

/**
 * This jQuery plugin displays pagination links inside the selected elements.
 *
 * @author Gabriel Birke (birke *at* d-scribe *dot* de)
 * @version 1.2
 * @param {int} maxentries Number of entries to paginate
 * @param {Object} opts Several options (see README for documentation)
 * @return {Object} jQuery Object
 */
jQuery.fn.pagination = function(maxentries, opts){
    opts = jQuery.extend({
        items_per_page:10,
        num_display_entries:10,
        current_page:0,
        num_edge_entries:0,
        link_to:"#",
        prev_text:"Prev",
        next_text:"Next",
        ellipse_text:"...",
        prev_show_always:true,
        next_show_always:true,
        callback:function(){return false;}
    },opts||{});
    
    return this.each(function() {
        /**
         * 计算最大分页显示数目
         */
        function numPages() {
            return Math.ceil(maxentries/opts.items_per_page);
        }    
        /**
         * 极端分页的起始和结束点,这取决于current_page 和 num_display_entries.
         * @返回 {数组(Array)}
         */
        function getInterval()  {
            var ne_half = Math.ceil(opts.num_display_entries/2);
            var np = numPages();
            var upper_limit = np-opts.num_display_entries;
            var start = current_page>ne_half?Math.max(Math.min(current_page-ne_half, upper_limit), 0):0;
            var end = current_page>ne_half?Math.min(current_page+ne_half, np):Math.min(opts.num_display_entries, np);
            return [start,end];
        }
        
        /**
         * 分页链接事件处理函数
         * @参数 {int} page_id 为新页码
         */
        function pageSelected(page_id, evt){
            current_page = page_id;
            drawLinks();
            var continuePropagation = opts.callback(page_id, panel);
            if (!continuePropagation) {
                if (evt.stopPropagation) {
                    evt.stopPropagation();
                }
                else {
                    evt.cancelBubble = true;
                }
            }
            return continuePropagation;
        }
        
        /**
         * 此函数将分页链接插入到容器元素中
         */
        function drawLinks() {
            panel.empty();
            var interval = getInterval();
            var np = numPages();
            // 这个辅助函数返回一个处理函数调用有着正确page_id的pageSelected。
            var getClickHandler = function(page_id) {
                return function(evt){ return pageSelected(page_id,evt); }
            }
            //辅助函数用来产生一个单链接(如果不是当前页则产生span标签)
            var appendItem = function(page_id, appendopts){
                page_id = page_id<0?0:(page_id<np?page_id:np-1); // 规范page id值
                appendopts = jQuery.extend({text:page_id+1, classes:""}, appendopts||{});
                if(page_id == current_page){
                    var lnk = jQuery("<span class='current'>"+(appendopts.text)+"</span>");
                }else{
                    var lnk = jQuery("<a>"+(appendopts.text)+"</a>")
                        .bind("click", getClickHandler(page_id))
                        .attr('href', opts.link_to.replace(/__id__/,page_id));        
                }
                if(appendopts.classes){lnk.addClass(appendopts.classes);}
                panel.append(lnk);
            }
            // 产生"Previous"-链接
            if(opts.prev_text && (current_page > 0 || opts.prev_show_always)){
                appendItem(current_page-1,{text:opts.prev_text, classes:"prev"});
            }
            // 产生起始点
            if (interval[0] > 0 && opts.num_edge_entries > 0)
            {
                var end = Math.min(opts.num_edge_entries, interval[0]);
                for(var i=0; i<end; i++) {
                    appendItem(i);
                }
                if(opts.num_edge_entries < interval[0] && opts.ellipse_text)
                {
                    jQuery("<span>"+opts.ellipse_text+"</span>").appendTo(panel);
                }
            }
            // 产生内部的些链接
            for(var i=interval[0]; i<interval[1]; i++) {
                appendItem(i);
            }
            // 产生结束点
            if (interval[1] < np && opts.num_edge_entries > 0)
            {
                if(np-opts.num_edge_entries > interval[1]&& opts.ellipse_text)
                {
                    jQuery("<span>"+opts.ellipse_text+"</span>").appendTo(panel);
                }
                var begin = Math.max(np-opts.num_edge_entries, interval[1]);
                for(var i=begin; i<np; i++) {
                    appendItem(i);
                }
                
            }
            // 产生 "Next"-链接
            if(opts.next_text && (current_page < np-1 || opts.next_show_always)){
                appendItem(current_page+1,{text:opts.next_text, classes:"next"});
            }
        }
        
        //从选项中提取current_page
        var current_page = opts.current_page;
        //创建一个显示条数和每页显示条数值
        maxentries = (!maxentries || maxentries < 0)?1:maxentries;
        opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0)?1:opts.items_per_page;
        //存储DOM元素,以方便从所有的内部结构中获取
        var panel = jQuery(this);
        // 获得附加功能的元素
        this.selectPage = function(page_id){ pageSelected(page_id);}
        this.prevPage = function(){ 
            if (current_page > 0) {
                pageSelected(current_page - 1);
                return true;
            }
            else {
                return false;
            }
        }
        this.nextPage = function(){ 
            if(current_page < numPages()-1) {
                pageSelected(current_page+1);
                return true;
            }
            else {
                return false;
            }
        }
        // 所有初始化完成,绘制链接
        drawLinks();
        // 回调函数
        //opts.callback(current_page, this);
    });
}

 准备测试数据:【switch case的使用,记住每一个case需要加break】:

Admin类加无参和全参的构造方法:

@Test
    public void insertAdmin(){
        //int i = 0;
        int temp = 0;
        for (int i = 0; i < 837; i++) {
            temp = i%10;
            switch(temp){
                case 0:adminMapper.insert(new Admin(null,"logAccount"+"000A","123123"+"000A","snnndd"+i,"email"+i,null));
                    break;
                case 1:adminMapper.insert(new Admin(null,"logAccount"+"000B","123123"+"000B","snnndd"+i,"email"+i,null));
                    break;
                case 2:adminMapper.insert(new Admin(null,"logAccount"+"000C","123123"+"000C","snnndd"+i,"email"+i,null));
                    break;
                case 3:adminMapper.insert(new Admin(null,"logAccount"+"000D","123123"+"000D","snnndd"+i,"email"+i,null));
                    break;
                case 4:adminMapper.insert(new Admin(null,"logAccount"+"000E","123123"+"000E","snnndd"+i,"email"+i,null));
                    break;
                case 5:adminMapper.insert(new Admin(null,"logAccount"+"000F","123123"+"000F","snnndd"+i,"email"+i,null));
                    break;
                case 6:adminMapper.insert(new Admin(null,"logAccount"+"000G","123123"+"000G","snnndd"+i,"email"+i,null));
                    break;
                case 7:adminMapper.insert(new Admin(null,"logAccount"+"000H","123123"+"000H","snnndd"+i,"email"+i,null));
                    break;
                case 8:adminMapper.insert(new Admin(null,"logAccount"+"000I","123123"+"000I","snnndd"+i,"email"+i,null));
                    break;
                case 9:adminMapper.insert(new Admin(null,"logAccount"+"000J","123123"+"000J","snnndd"+i,"email"+i,null));
                    break;

            }

        }
        System.out.println("准备数据完毕。。。。");

    }

 

posted @ 2020-03-23 20:36  lxw-all  阅读(657)  评论(0编辑  收藏  举报