mybatis分页插件的使用

一 . 在maven中引入pagehelper相关依赖包

		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>5.1.2</version>
		</dependency>

二 . 在applicationContext.xml中注册mybatis插件(mybatis要与spring整合)

	<!-- 5.配置mybatis -->
	<bean id="sqlSessionFactory"
		class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- mapperLocations:指定mapper配置文件的位置(相当于Dao的实现类),根据自己项目修改 -->
		<property name="mapperLocations" value="classpath:mapper/*xml"></property>
		<property name="plugins">
			<array>
				<bean class="com.github.pagehelper.PageInterceptor">
					<property name="properties">
						<!--使用下面的方式配置参数,一行配置一个 -->
						<value>
							helperDialect=mysql
						</value>
					</property>
				</bean>
			</array>
		</property>
	</bean>
 
	<!-- 扫描Mapper(Dao)接口,根据自己的项目修改-->
	<mybatis-spring:scan base-package="com.tansen.selecting.mapper"/>

编写mapper映射文件(Dao接口的实现类,Dao接口以及Service省略)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  <!--namespace 写接口的全类名 ,根据自己项目修改 -->
<mapper namespace="com.tansen.selecting.mapper.CourseMapper">

	<!-- List<Course> getAllCourses(); -->
	<!-- resultType为返回值类型,集合则返回集合的实体类型 -->
	<select id="getCourseNameLike"
		resultType="com.tansen.selecting.entities.Course">
		select * from course where name like "%"#{name}"%"
	</select>

</mapper>

三 .编写Controller类

	@RequestMapping("/findByNameLike")//模糊查询
	public ModelAndView findByNameLike(@RequestParam(value="pn",required=false,defaultValue="1") Integer pn, @RequestParam("name") String name) {
		PageHelper.startPage(pn,5);//第一个参数表示第几页,第二个参数表示每页显示的记录数
		List<Course> courses = courseService.getCourseNameLike(name);//查询
		PageInfo pageInfo = new PageInfo<>(courses,5);//用PageInfo对结果进行包装,第二个参数表示前端显示的页数
		ModelAndView view = new ModelAndView("teacher_main");
		view.addObject("name", name);
		view.addObject("pageInfo", pageInfo);
		view.addObject("pn",pageInfo.getPageNum());
		return view;
	}

四. 编写jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>Insert title here</title>
</head>
<script type="text/javascript">
	function function1() {
		window.location.href = "${pageContext.request.contextPath}/course/addPage";
	}
</script>
<body>
	<button onclick="function1()">新增课程</button>
	<br>




	<form action="${pageContext.request.contextPath}/course/findByNameLike"
		method="post">
		<input type="text" name="name"> <input type="submit"
			value="查找课程">
	</form>
	<br>
	
	
	<table border="1">
		<tr>
			<th>课程号</th>
			<th>课程名称</th>
			<th>课程授课老师</th>
			<th>教师容量</th>
			<th>当前选课人数</th>
			<th>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp操作&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</th>
		</tr>
		<c:forEach items="${pageInfo.list}" var="pageInfo">
			<tr>
				<td>${pageInfo.id}</td>
				<td>${pageInfo.name}</td>
				<td>${pageInfo.teacher}</td>
				<td>${pageInfo.capacity}</td>
				<td>${pageInfo.number}</td>
				<td><a
					href="${pageContext.request.contextPath}/course/editPage?id=${pageInfo.id}&name=${pageInfo.name}&teacher=${pageInfo.teacher}">修改</a></td>
				<td><a
					href="${pageContext.request.contextPath}/course/delete?id=${pageInfo.id}&pn=${pageNum}">删除</a></td>
				<td><a href="">管理当前选课</a></td>
			</tr>
		</c:forEach>
	</table>
	
	<c:choose>
		<c:when test="${pageInfo.hasPreviousPage}">
			<a
				href="${pageContext.request.contextPath}/course/findByNameLike?pn=${pageInfo.pageNum-1}&name=${name}">上一页</a>
		</c:when>
		<c:otherwise>
			<a href="javascript:void(0);">上一页</a>
		</c:otherwise>
	</c:choose>


	<c:forEach items="${pageInfo.navigatepageNums}" var="page_num">
		<c:if test="${page_num == pageInfo.pageNum}">
			<a href=" ">${page_num}</a>
		</c:if>
		<c:if test="${page_num != pageInfo.pageNum}">
			<a
				href="${pageContext.request.contextPath}/course/teacherFindAll?pn=${page_num}">${page_num}</a>
		</c:if>
	</c:forEach>


	<c:choose>
		<c:when test="${pageInfo.hasNextPage}">
		<a
			href="${pageContext.request.contextPath}/course/findByNameLike?pn=${pageInfo.pageNum+1}&name=${name}">下一页</a>
		</c:when>
		<c:otherwise>
		<a href="javascript:void(0);">下一页</a>
		</c:otherwise>
	</c:choose>
	
		共${pageInfo.pages}页,一共${pageInfo.total}条记录,到第
		<form
			action="${pageContext.request.contextPath}/course/teacherFindAll"
			method="post">
			<input type="text" name="pn">页 <input type="submit"
				value="确定">
		</form>
</body>
</html>

注意:前端页面中${pageInfo.属性}中的属性必须和数据库中的字段用驼峰命名法或者resultMap建立映射关系,否则前端获取不到值

五. PageInfo类的说明

public class PageInfo<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    //当前页
    private int pageNum;
    //每页的数量
    private int pageSize;
    //当前页的数量
    private int size;
 
    //由于startRow和endRow不常用,这里说个具体的用法
    //可以在页面中"显示startRow到endRow 共size条数据"
 
    //当前页面第一个元素在数据库中的行号
    private int startRow;
    //当前页面最后一个元素在数据库中的行号
    private int endRow;
    //总记录数
    private long total;
    //总页数
    private int pages;
    //结果集
    private List<T> list;
 
    //前一页
    private int prePage;
    //下一页
    private int nextPage;
 
    //是否为第一页
    private boolean isFirstPage = false;
    //是否为最后一页
    private boolean isLastPage = false;
    //是否有前一页
    private boolean hasPreviousPage = false;
    //是否有下一页
    private boolean hasNextPage = false;
    //导航页码数
    private int navigatePages;
    //所有导航页号
    private int[] navigatepageNums;
    //导航条上的第一页
    private int navigateFirstPage;
    //导航条上的最后一页
    private int navigateLastPage;
 
    public PageInfo() {
    }
 
    /**
     * 包装Page对象
     *
     * @param list
     */
    public PageInfo(List<T> list) {
        this(list, 8);
    }
 
    /**
     * 包装Page对象
     *
     * @param list          page结果
     * @param navigatePages 页码数量
     */
    public PageInfo(List<T> list, int navigatePages) {
        if (list instanceof Page) {
            Page page = (Page) list;
            this.pageNum = page.getPageNum();
            this.pageSize = page.getPageSize();
 
            this.pages = page.getPages();
            this.list = page;
            this.size = page.size();
            this.total = page.getTotal();
            //由于结果是>startRow的,所以实际的需要+1
            if (this.size == 0) {
                this.startRow = 0;
                this.endRow = 0;
            } else {
                this.startRow = page.getStartRow() + 1;
                //计算实际的endRow(最后一页的时候特殊)
                this.endRow = this.startRow - 1 + this.size;
            }
        } else if (list instanceof Collection) {
            this.pageNum = 1;
            this.pageSize = list.size();
 
            this.pages = this.pageSize > 0 ? 1 : 0;
            this.list = list;
            this.size = list.size();
            this.total = list.size();
            this.startRow = 0;
            this.endRow = list.size() > 0 ? list.size() - 1 : 0;
        }
        if (list instanceof Collection) {
            this.navigatePages = navigatePages;
            //计算导航页
            calcNavigatepageNums();
            //计算前后页,第一页,最后一页
            calcPage();
            //判断页面边界
            judgePageBoudary();
        }
    }
 
 
.......
}


猜你喜欢

转载自blog.csdn.net/laogay_tansen/article/details/80898913