SSSM2---分页查询-pagehelper

后端要做的

  1. pom.xml中导入依赖
<dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.0.0</version>
    </dependency>
  1. mybatis-config.xml中配置plugin
  <plugins>
   <plugin interceptor="com.github.pagehelper.PageInterceptor">
     <property name="reasonable" value="true"></property>
   </plugin>
  </plugins>

3.Controller中引入pageHelper插件对紧邻的查询进行分页 然后将结果加入JSON中

 @RequestMapping("/all")
    @ResponseBody
    public Msg showAllWithJson(@RequestParam(value = "pn",defaultValue = "1")Integer pn)
    {
        PageHelper.startPage(pn,5);
        List<Employee> emList=employeeService.showAll();
        PageInfo<Employee> page=new PageInfo(emList,5);
        return Msg.success().add("pageInfo",page);
    }
  1. 上面的Controller分页显示查询结果的函数 要加上页数的形参 其中页数我们使用@requestparam这个注解有很多作用,其中一个就是可以为值设置默认值。
    在这里插入图片描述
    页数都是默认从第一页开始 在用户为操作之前我们就设置页数为1
    分页只对紧邻他的第一个查询进行分页
    在这里插入图片描述

pageinfo作为包装类 他的强大之处

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

使用json将分页信息包装返回

json可以做到平台无关性 因为只有浏览器是进行?=拼接的

  • 一般都要封装一个Msg类 里面封装一个HashMap来承装<code , msg >返回给客户端的状态和信息具体内容
public class Msg {
 private Map<String, Object> extend = new HashMap<>();
    private int code;
    private String msg;
    //省略了get set 方法
    public static Msg success() {
        Msg reslut = new Msg();
        reslut.setCode(100);
        reslut.setMsg("json字符串处理成功");
        return reslut;
    }
    public static Msg faliure() {
        Msg reslut = new Msg();
        reslut.setCode(200);
        reslut.setMsg("json字符串处理失败");
        return reslut;
    }

    public Msg add(String key, Object value) {
        this.getExtend().put(key, value);
        return this;
    }
  • 还要有方法add(String key, Object value)在controller中便于将返回的pageInfo(或者是list…因为pageInfo里面包含了我们所有的想要显示给前端的结果 )添加到map中
    在这里插入图片描述
  • 前端通过获取后端返回的json字符串,都在map中包装,在通过map.获取里面的pageInfo 再获取里面的内容
    在这里插入图片描述
    data里面是前端传给后端的页面数
    function里面的形参是后端传给前端的结果
    在这里插入图片描述
关于时间戳类型数据如何以json形式传却不乱码
<!-- $(function () {
        $.ajax({
            url:"${APP_PATH}/em/all",
            type:"GET",
            data:"1",
            success:function (result) {
                console.log(result);
                <!--解析员工属性-->
                build_table(result);
                build_page(result);
                build_page_nav(result);
            }
        });
    }); -->

详细来看一下前端页面

< head >头部引入基本的css js 资源

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>员工列表</title>
    <% pageContext.setAttribute("APP_PATH",request.getContextPath());%>

    <!-- Bootstrap css-->
    <link href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
    <script type="text/javascript" src="${APP_PATH}/static/jquery/jquery.min.js"></script>
    <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
    <script src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>

< body >体 分析页面的整体< container >分为几部分
注意< div >标签就是负责管理整个区域 并且一个< div>代表一部分
container 先分 row 再根据细节分 col

<body>
            <div class="container">
 <div class="row">
     <div class="col-md-8 col-md-offset-8"></div>
 </div>
  <div class="row"></div>
  <div class="row"></div> 
          </div>
</body>

在这里插入图片描述
来看上面的分4行 一些细节还有分列 3就是一个大表格

  • 基础只适合网页 采用字符串拼接的方式跳转页面
    获取后台的数据都是用el 来 获 取 使 用 j s t l 的 ‘ < c : f o r E a c h i t e m s = " {}来获取 使用jstl的`<c:forEach items=" 使jstl<c:forEachitems="{pageInfo.list}" var=“emp”>`等
    其中的class 按钮或者表格的列位置等样式前往bootstrap来选择需要的就行。
  • 包括上一页下一页的判断都用< c: if test>等即可
<body>
    <div class="container">
 
    <div class="row">
        <div class="col-md-12">
        <h1>SSM-CRUD</h1>
        </div>
    </div>

  <div class="row">
            <div class="col-md-8 col-md-offset-8">
                <button class="btn btn-primary">新增</button>
                <button class="btn btn-danger">删除</button>
            </div>
 </div>
     
<div class="row">
            <div class="col-md-12">
                <table  class="table table-hover">
                    <tr>
                        <th>#</th>
                        <th>员工姓名</th>
                        <th>性别</th>
                        <th>E-mail</th>
                        <th>入职时间</th>
                        <th>所在部门</th>
                        <th>操作</th>
                    </tr>
      <c:forEach items="${pageInfo.list}" var="emp">
                        <tr>
                            <td>${emp.eid}</td>
                            <td>${emp.name}</td>
                            <td>${emp.gender=="M"?"男":"女"}</td>
                            <td>${emp.email}</td>
                            <td>${emp.inday}</td>
                            <td>${emp.department.dname}</td>
                            <td>
             <button class="btn btn-primary btn-sm">
            <span class="glyphicon glyphicon-pencil " aria-hidden="true"></span>新增
            </button>
                <button class="btn btn-danger btn-sm">
            <span class="glyphicon glyphicon-trash " aria-hidden="true"></span>  删除   </button>
                            </td>
                        </tr>
                    </c:forEach>
                </table>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6">
            当前第${pageInfo.pageNum}页|共${pageInfo.pages}页|共${pageInfo.total}条记录
            </div>
            <div class="col-md-6">
                <nav aria-label="Page navigation">
                    <ul class="pagination">
                        <li><a href="${APP_PATH}/em/all?pn=1">首页</a></li>

                        <c:if test="${pageInfo.hasPreviousPage}">
                            <li>
                                <a href="${APP_PATH}/em/all?pn=${pageInfo.pageNum-1}" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                        </c:if>

                       <c:forEach items="${pageInfo.navigatepageNums}" var="page_Num">
                          <c:if test="${page_Num==pageInfo.pageNum}">
                           <li class="active"><a href="#">${page_Num}</a></li>
                          </c:if>
                           <c:if test="${page_Num != pageInfo.pageNum}">
                               <li><a href="${APP_PATH}/em/all?pn=${page_Num}">${page_Num}</a></li>
                           </c:if>
                       </c:forEach>

                         <c:if test="${pageInfo.hasNextPage}">
                        <li>
                            <a href="${APP_PATH}/em/all?pn=${pageInfo.pageNum+1}" aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        </li>
                         </c:if>
                        <li><a href="${APP_PATH}/em/all?pn=${pageInfo.pages}">末页</a></li>
                    </ul>
                </nav>
        </div>
    </div>
    </div>
</body>
  • 使用ajax方式进入后台 不是用拼接的url 而是自己设定的 前台的请求通过data传递
  • 进行对返回结果的处理不再用el表达式获取 而是通过success:function(reslut)对形参reslut的属性获取进行具体的处理和操作
  • 遍历不是用c:for each使用js的$.each()
    最简单的对比就是上一页下一页的操作 拼接是采用-1等 会跳转页面 而ajax不采用单击事件 调用topage函数
    在这里插入图片描述
    在这里插入图片描述
    ajax方式的代码和上面的拼接版本 关于静态资源的引入和 区域的划分都是一致的
    他将c:foreach等都抽取成函数 function 将返回结果或者处理结果的都变成函数 并且以table等作为结果返回的内容加了id 用于最后appendTo
<div class="row">
        <div class="col-md-12">
            <table  class="table table-hover" id="emps_table">
                <thead>
                <tr>
                    <th>#</th>
                    <th>员工姓名</th>
                    <th>性别</th>
                    <th>E-mail</th>
                    <th>入职时间</th>
                    <th>所在部门</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
      /**
     * 解析显示员工信息
     * */
function build_emps_table(result) {
        $("#emps_table tbody").empty();
        var emps = result.extend.pageInfo.list;
        $.each(emps, function (index, item) {
            var checkBoxTd = $("<td><input type='checkbox' class='check_item'></input></td>");
            var empNameTd = $("<td></td>").append(item.name);
            var genderTd = $("<td></td>").append(item.gender=="M"?"男":"女");
            var emailTd = $("<td></td>").append(item.email);
            var indayTd=$("<td></td>").append(item.inday);
            var deptNameTd = $("<td></td>").append(item.department.dname);
            var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-pencil"))
                .append("编辑");
            editBtn.attr("edit-id", item.eid);
            var delBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-trash"))
                .append("删除");
            delBtn.attr("del-id", item.eid);
            var btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn);
            $("<tr></tr>")
                .append(checkBoxTd)
                .append(empNameTd)
                .append(genderTd)
                .append(emailTd)
                .append(indayTd)
                .append(deptNameTd)
                .append(btnTd)
                .appendTo("#emps_table tbody");
        });
    }
 <!--第四行  页面的一些记录 以及 显示页数  -->
    <div class="row">
        <div class="col-md-6" id="page_info_area"></div>
        <div class="col-md-6" id="page_nav_area"></div>
    </div>
     /**
     * 解析显示分页信息
     * @param result
     */
    function build_page_info(result) {
        $("#page_info_area").empty();
        $("#page_info_area").append("当前"
            + result.extend.pageInfo.pageNum
            + "第页,总"
            + result.extend.pageInfo.pages
            + "页,总共"
            + result.extend.pageInfo.total
            + "有条记录")
        totalRecord = result.extend.pageInfo.total;
        currentPage = result.extend.pageInfo.pageNum;
    }
    /**
     * 解析显示分页条
     * @param result
     */
    function build_page_nav(result) {
        $("#page_nav_area").empty();
        var ul = $("<ul></ul>").addClass("pagination");
        var firstPageLi = $("<li></li>")
            .append($("<a></a>").append("首页").attr("href", "#"));
        var prePageLi = $("<li></li>")
            .append($("<a></a>").append("&laquo;"));
        if (!result.extend.pageInfo.hasPreviousPage) {
            firstPageLi.addClass("disabled");
            prePageLi.addClass("disabled");
        } else {
            firstPageLi.click(function () {
                to_page(1);
            });
            prePageLi.click(function () {
                to_page(result.extend.pageInfo.pageNum - 1);
            });
        }
        var nextPageLi = $("<li></li>")
            .append($("<a></a>").append("&raquo;"));
        var lastPageLi = $("<li></li>")
            .append($("<a></a>").append("尾页").attr("href", "#"));
        if (!result.extend.pageInfo.hasNextPage) {
            lastPageLi.addClass("disabled");
            nextPageLi.addClass("disabled");
        } else {
            lastPageLi.click(function () {
                to_page(result.extend.pageInfo.pages);
            });
            nextPageLi.click(function () {
                to_page(result.extend.pageInfo.pageNum + 1);
            });
        }
        ul.append(firstPageLi).append(prePageLi);
        $.each(result.extend.pageInfo.navigatepageNums, function (index, item) {
            var numLi = $("<li></li>")
                .append($("<a></a>").append(item));
            if (result.extend.pageInfo.pageNum == item) {
                numLi.addClass("active");
            }
            numLi.click(function () {
                to_page(item)
            });
            ul.append(numLi);
        });
        ul.append(nextPageLi).append(lastPageLi);
        var navEle = $("<nav></nav>").append(ul);
        $("#page_nav_area").append(navEle);
    }

最后当进入页面的时候就直接用ajax跳转 将所有的function都进行合并然后显示

 $(function () {
        to_page(1);
    });
    function to_page(pn) {
        $.ajax({
            url: "${APP_PATH}/em/all",
            data: "pn=" + pn,
            type: "GET",
            success: function (result) {
                console.log(result);
                build_emps_table(result);
                build_page_info(result);
                build_page_nav(result)
            }
        });
    }

基本 的思想就是 首先选择好你的容器 按钮 还是 表格 容器要设置id
操作容器触发事件 onclick函数触发回调函数function $("id").click(function(){})

加深上面的思想流程

有一个下拉表单的容器

 <div class="form-group">
                        <label  class="col-sm-2 control-label">department</label>
                        <div class="col-sm-10">
                            <select class="form-control" name="departmentid" id="dept_select">
                        </select>
                        </div>
                    </div>

做一个函数处理后端返回过来的结果
可以在其他的函数或者点击事件中调用这个函数
当前的函数的结果都appendTo容器的”#id“里面

 function get_department()
        {
            $.ajax({
                url:"${APP_PATH}/depts",
                type:"GET",
                success:function(result)
                {
                    $.each(result.extend.dept, function () {
                        var optionEle = $("<option></option>").append(this.dname).attr("value", this.departmentid);
                        optionEle.appendTo("#dept_select");
                    });
                }
            });
        }

通常就是我们先设想希望这里要个什么容器(按钮/表单/下拉链表…)
然后用什么函数调用这个容器 或者将函数的返回结果appendTo到容器
调用的时候就用#容器id

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值