天天看點

Mybatis-PageHelper插件實作分頁

(一)使用PageHelper分頁插件的基本配置

參考:MyBatis 分頁插件 PageHelper

參考 : PageHelper作者部落格文章學習

1.在 pom.xml中引入依賴Jar包

<!-- mybatis-pageHelper -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.0.0</version>
</dependency>
           

2.在mybatis-config.xml中配置PageInterceptor攔截器

<!--2.配置分頁插件,此插件必須配置在typeAliases後面-->
<plugins>
     <plugin interceptor="com.github.pagehelper.PageInterceptor">
<!--分頁合理化參數,預設文false;pageNum<=0,查詢第一頁;pageNum>總頁數,查詢最後一頁-->
         <property name="reasonable" value="true"/>
    </plugin>
</plugins>
           

3.EmployeeControlller.java服務端程式

@Controller
public class EmployeeControlller {

    @Autowired
    EmployeeService employeeService;
    @RequestMapping("/emps")
    public String getEmps(@RequestParam(value="pn",defaultValue="1")Integer pn,Model model) {
        //1.使用PageHelper分頁插件,在查詢之前隻需傳入頁碼及每頁顯示的資料記錄參數即可!
        PageHelper.startPage(pn, );
        //2.startPage後緊跟的就是一個分頁查詢
        List<Employee> emps=employeeService.getAll();
        //3.使用PageInfo封裝查詢結果,隻需将PageInfo交給頁面即可
        //4.PageInfo封裝分頁的詳細資訊
        //5. PageInfo構造器的5表示連續顯示的頁碼數字
        PageInfo<Employee> page=new PageInfo<Employee>(emps,);
        model.addAttribute("pageInfo", page);
        return "list";

    }

}
           

4.使用Spring-Test測試子產品:模拟浏覽器向伺服器發送請求

package com.wang.ssm.test;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.github.pagehelper.PageInfo;
import com.wang.ssm.bean.Employee;

/*
 * spring4的測試需要servlet-api 3.0以上版本
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
//引入spring-bean.xml,springmvc.xml檔案
@ContextConfiguration(locations={"classpath:spring-bean.xml","classpath:springmvc.xml"})
public class SpringMVCTest {
    @Autowired
    WebApplicationContext context;
    MockMvc mvc; //虛拟springmvc

    @Before
    public void initMockMvc(){
        //首先初始化
        mvc=MockMvcBuilders.webAppContextSetup(context).build();
    }
    @Test
    public void page() throws Exception{
        //MockMvcRequestBuilders模拟浏覽器向伺服器發送請求
        MvcResult result=mvc.perform(MockMvcRequestBuilders.get("/emps").param("pn", "1")).andReturn();

        //伺服器端傳回給浏覽器的資料
        MockHttpServletRequest request=result.getRequest();
        @SuppressWarnings("unchecked")
        //擷取pageInfo封裝的資料
        PageInfo<Employee> info=(PageInfo<Employee>) request.getAttribute("pageInfo");

        //info調用以下資料可以擷取分頁資訊
        System.out.println("目前頁碼="+info.getPageNum());
        System.out.println("總頁碼="+info.getPages());
        System.out.println("每頁的個數="+info.getSize());
        System.out.println("總記錄數="+info.getTotal());
        System.out.println("連續顯示的頁碼數字");
        int[]pages=info.getNavigatepageNums();
        for(int i:pages) {
            System.out.print(i+",");
        }
        System.out.println("顯示目前頁碼所顯示的員工資料:");
        List<Employee> list=info.getList();
        for(Employee e:list){
            System.out.println(e);
        }
    }
}
           

(二)PageHelp實作前台分頁功能

項目結構:

Mybatis-PageHelper插件實作分頁
Mybatis-PageHelper插件實作分頁
Mybatis-PageHelper插件實作分頁

注:下載下傳項目源碼

1.前端實作分頁源碼(背景源碼在上面以展示)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>員工清單</title>
<!-- 
    web資源的路徑問題,不是以/開始的都是相對路徑,/代表站點根目錄
 -->
<%
    pageContext.setAttribute("path", request.getContextPath());
%>
<link rel="stylesheet"
    href="${path}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
<script type="text/javascript"
    src="${path }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script type="text/javascript"
    src="${path }/static/js/jquery-1.12.4.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <h1>SSM示範</h1>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4 col-md-offset-0">
                <button class="btn btn-primary">增加</button>
                 <button class="btn btn-warning">删除</button> 
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <table class="table table-hover" border="2">
                    <tr>
                        <th>編号</th>
                        <th>姓名</th>
                        <th>性别</th>
                        <th>郵箱</th>
                        <th>所屬部門</th>
                        <th>操作</th>
                    </tr>
                    <c:forEach items="${pageInfo.list }" var="emp">
                        <tr>
                            <td>${emp.empId }</td>
                            <td>${emp.empName }</td>
                            <td>${emp.gender=="M"?"男":"女" }</td>
                            <td>${emp.email }</td>
                            <td>${emp.department.deptName }</td>
                            <td>
                                <button class="btn btn-primary btn-sm">
                                    <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
                                    增加
                                </button>
                                <button class="btn btn-warning 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="${path }/emps?pn=1">首頁</a></li>
                    <c:if test="${pageInfo.hasPreviousPage }">
                        <li>
                            <a href="${path }/emps?pn=${pageInfo.pageNum-1}" aria-label="Previous"> 
                                <span aria-hidden="true">&laquo;</span>
                            </a>
                        </li>
                    </c:if>
                    <c:forEach items="${pageInfo.navigatepageNums }" var="page">
                        <c:if test="${page==pageInfo.pageNum }">
                            <li class="active"><a href="${path }/emps?pn=${page}">${page}</a></li>
                        </c:if>
                        <c:if test="${page!=pageInfo.pageNum }">
                            <li><a href="${path }/emps?pn=${page}">${page}</a></li>
                        </c:if>
                    </c:forEach>
                    <c:if test="${pageInfo.hasNextPage }">
                        <li>
                            <a href="${path }/emps?pn=${pageInfo.pageNum+1 }" aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        </li>
                    </c:if>

                    <li><a href="${path }/emps?pn=${pageInfo.pages}">末頁</a></li>
                </ul>
                </nav>
            </div>
        </div>
    </div>
</body>
</html>