jsp 页面实现分页

本文介绍了如何在JSP中使用PageHelper进行分页操作,包括在Pom.xml中添加依赖,将pageUtil包拷贝到指定目录,配置mybatis的applicationContext和mybatis-config,放置js包,更新分页页面,拷贝listPage.js,编写控制器分页方法及重写实现层。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.1 Pom.xml文件中加入pagehelper依赖

<!-- 分页 -->
		<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>4.1.5</version>
		</dependency>
		<dependency>
			<groupId>jsptags</groupId>
			<artifactId>pager-taglib</artifactId>
			<version>2.0</version>
		</dependency>

1.2 把包pageUtil拷贝到framework.utils目录下

在这里插入图片描述

1.3 applicationContext-fy.xml拷贝到mybatis文件中

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL MAP Config 3.1//EN" 
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<setting name="callSettersOnNulls" value="true" />
	</settings>
	<!-- 配置分页插件 -->
	<plugins>
		<!-- com.github.pagehelper为PageHelper类所在包名 -->
		<plugin interceptor="com.github.pagehelper.PageHelper">
			<!--方言: 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库 -->
			<property name="dialect" value="mysql" />
		</plugin>
	</plugins>
</configuration>

1.4 在mybatis-config中添加如下代码

		<!-- 分页相关 -->
		<setting name="callSettersOnNulls" value="true" />
	</settings>

	<!-- 分页相关 -->
	<plugins>
		<!-- com.github.pagehelper为PageHelper类所在包名 -->
		<plugin interceptor="com.github.pagehelper.PageHelper">
			<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库 -->
			<property name="dialect" value="mysql" />
		</plugin>
	</plugins>

1.5 把js包放到webapp应用下面

在这里插入图片描述

1.6 在分页页面中加入相应插件js和csss,并增加其他部分

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<!-- 增加1 -->



<%-- 分页相关 --%>
<script type="text/javascript" src="<%=basePath%>js/jquery.js"></script>
<script type="text/javascript" src="<%=basePath%>js/kkpager/jpager.js"></script>
<link rel="stylesheet" type="text/css"
	href="<%=basePath%>js/kkpager/jpager.css">
<script type="text/javascript"
	src="<%=basePath%>view/system/user/listPage.js"></script>
<script type="text/javascript">
        function load() {
        	arrayPage(${pageResult.pages},${pageResult.total});
        }
</script>





</head>
<body onload="load()"><!-- 增加2-->







	<div align="center">
		<h1>用户列表页面</h1>
		<hr>
		<form method="post" action="">
			<div>
				<table align="center" border="1" width="80%">
					<tr>
						<td>用户ID</td>
						<td>名称</td>
						<td>年龄</td>
						<td>性别</td>
						<td>爱好</td>
						<td>登录名</td>
						<td>密码</td>
						<td>创建时间</td>
					</tr>







<!--<c:forEach items="${userList}" var="user"><!-- 增加3 -->






					<c:forEach items="${pageResult.dataList}" var="user"><!-- 增加3 -->
						<tr>
							<td><input type="checkbox" name="id[]"
								value="${user.userId }" />${user.userId }</td>
							<td>${user.name }</td>
							<td>${user.age }</td>
							<td>${user.sex }</td>
							<td>${user.hobby }</td>
							<td>${user.loginName }</td>
							<td>${user.password }</td>
							<td><fmt:formatDate value="${user.createTime }"
									pattern="yyyy-MM-dd HH:ss:mm" /></td>
						</tr>
					</c:forEach>
				</table>
			</div>







			<div align="center" id="jpager"></div><!-- 增加4 -->










		</form>
	</div>
</body>
</html>

1.7 拷贝listPage.js

1.8 在控制器写分页方法

public ModelAndView listPage(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
		System.out.println("------------------传统---------------------");
		ModelAndView mv = new ModelAndView();
		// 当前页和每页的条数
		// 传入数据到分页工具类
		PagedResult<User> pageResult = userService.getAllByPage(pageNumber, pageSize);
		// 数据传递到前台页面展示层
		mv.addObject("pageResult", pageResult);
		mv.setViewName("system/user/userList");
		return mv;
	}

1.9 重写实现层

// 1.调用分页插件
		PageHelper.startPage(pageNumber, pageSize);
		// 2.查询数据库,获取数据
		List<User> userlist = userMapper.queryAllUser();
		// 3.通过分页工具类加载分页数据
		return PageBeanUtil.toPagedResult(userlist);

/* * @(#)PageControl.java 1.00 2004-9-22 * * Copyright 2004 2004 . All rights reserved. * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.hexiang.utils; /** * PageControl, 分页控制, 可以判断总页数和是否有上下页. * * 2008-07-22 加入输出上下分页HTML代码功能 * * @author HX * @version 1.1 2008-9-22 */ public class PageBean { /** 每页显示记录数 */ private int pageCount; /** 是否有上一页 */ private boolean hasPrevPage; /** 记录总数 */ private int recordCount; /** 是否有下一页 */ private boolean hasNextPage; /**总页面数 */ private int totalPage; /** 当前页码数 */ private int currentPage; /** * 分页前的页面地址 */ private String pageUrl; /** * 输出分页 HTML 页面跳转代码, 分链接和静态文字两种. * 2008-07-22 * @return HTML 代码 */ public String getPageJumpLinkHtml() { if(StringUtil.isEmpty(pageUrl)) { return ""; } // 检查是否有参数符号, 没有就加上一个? if(pageUrl.indexOf('?') == -1) { pageUrl = pageUrl + '?'; } StringBuffer buff = new StringBuffer("<span id='pageText'>"); // 上一页翻页标记 if(currentPage > 1) { buff.append("[ <a href='" + pageUrl + "&page=" + (currentPage - 1) + "' title='转到第 " + (currentPage - 1) + " 页'>上一页</a> ] "); } else { buff.append("[ 上一页 ] "); } // 下一页翻页标记 if(currentPage < getTotalPage()) { buff.append("[ <a href='" + pageUrl + "&page=" + (currentPage + 1)+ "' title='转到第 " + (currentPage + 1) + " 页'>下一页</a> ] "); } else { buff.append("[ 下一页 ] "); } buff.append("</span>"); return buff.toString(); } /** * 输出页码信息: 第${currentPage}页/共${totalPage}页 * @return */ public String getPageCountHtml() { return "第" + currentPage + "页/共" + getTotalPage() + "页"; } /** * 输出 JavaScript 跳转函数代码 * @return */ public String getJavaScriptJumpCode() { if(StringUtil.isEmpty(pageUrl)) { return ""; } // 检查是否有参数符号, 没有就加上一个? if(pageUrl.indexOf("?") == -1) { pageUrl = pageUrl + '?'; } return "<script>" + "// 页面跳转函数\n" + "// 参数: 包含页码的表单元素,例如输入框,下拉框等\n" + "function jumpPage(input) {\n" + " // 页码相同就不做跳转\n" + " if(input.value == " + currentPage + ") {" + " return;\n" + " }" + " var newUrl = '" + pageUrl + "&page=' + input.value;\n" + " document.location = newUrl;\n" + " }\n" + " </script>"; } /** * 输出页面跳转的选择框和输入框. 示例输出: * <pre> 转到 <!-- 输出 HTML SELECT 元素, 并选中当前页面编码 --> <select onchange='jumpPage(this);'> <c:forEach var="i" begin="1" end="${totalPage}"> <option value="${i}" <c:if test="${currentPage == i}"> selected </c:if> >第${i}页</option> </c:forEach> </select> 输入页码:<input type="text" value="${currentPage}" id="jumpPageBox" size="3"> <input type="button" value="跳转" onclick="jumpPage(document.getElementById('jumpPageBox'))"> </pre> * @return */ public String getPageFormJumpHtml() { String s = "转到\n" + "\t <!-- 输出 HTML SELECT 元素, 并选中当前页面编码 -->\n" + " <select onchange='jumpPage(this);'>\n" + " \n"; for(int i = 1; i <= getTotalPage(); i++ ) { s += "<option value=" + i + "\n"; if(currentPage == i) { s+= " selected "; } s += "\t>第" + i + "页</option>\n"; } s+= " </select>\n" + " 输入页码:<input type=\"text\" value=\"" + currentPage + "\" id=\"jumpPageBox\" size=\"3\"> \n" + " <input type=\"button\" value=\"跳转\" onclick=\"jumpPage(document.getElementById('jumpPageBox'))\"> "; return s; } /** * 进行分页计算. */ private void calculate() { if (getPageCount() == 0) { setPageCount(1); } totalPage = (int) Math.ceil(1.0 * getRecordCount() / getPageCount()); // 总页面数 if (totalPage == 0) totalPage = 1; // Check current page range, 2006-08-03 if(currentPage > totalPage) { currentPage = totalPage; } // System.out.println("currentPage=" + currentPage); // System.out.println("maxPage=" + maxPage); // // Fixed logic error at 2004-09-25 hasNextPage = currentPage < totalPage; hasPrevPage = currentPage > 1; return; } /** * @return Returns the 最大页面数. */ public int getTotalPage() { calculate(); return totalPage; } /** * @param currentPage * The 最大页面数 to set. */ @SuppressWarnings("unused") private void setTotalPage(int maxPage) { this.totalPage = maxPage; } /** * 是否有上一页数据 */ public boolean hasPrevPage() { calculate(); return hasPrevPage; } /** * 是否有下一页数据 */ public boolean hasNextPage() { calculate(); return hasNextPage; } // Test public static void main(String[] args) { PageBean pc = new PageBean(); pc.setCurrentPage(2); pc.setPageCount(4); pc.setRecordCount(5); pc.setPageUrl("product/list.do"); System.out.println("当前页 " + pc.getCurrentPage()); System.out.println("有上一页 " + pc.hasPrevPage()); System.out.println("有下一页 " + pc.hasNextPage()); System.out.println("总页面数 " + pc.getTotalPage()); System.out.println("分页 HTML 代码 " + pc.getPageJumpLinkHtml()); } /** * @return Returns the 当前页码数. */ public int getCurrentPage() { return currentPage; } /** * 设置当前页码, 从 1 开始. * @param currentPage * The 当前页码数 to set. */ public void setCurrentPage(int currentPage) { if (currentPage <= 0) { currentPage = 1; } this.currentPage = currentPage; } /** * @return Returns the recordCount. */ public int getRecordCount() { return recordCount; } /** * @param recordCount * The recordCount to set. */ public void setRecordCount(int property1) { this.recordCount = property1; } /** * @return Returns the 每页显示记录数. */ public int getPageCount() { return pageCount; } /** * @param pageCount * The 每页显示记录数 to set. */ public void setPageCount(int pageCount) { this.pageCount = pageCount; } public String getPageUrl() { return pageUrl; } public void setPageUrl(String value) { pageUrl = value; } }
JspPageControlor分页插件使用说明 1、次插件将数据库查询和分页操作分离开,在查询的时候,不管采用什么设计模式,都必须实现 PageListener接口。 2、接口里面包含四个方法 (1)、publicListdoSelect(intrecordStart,intsizePage),参数recordStart表示从第几条 记录开始查询。参数sizePage表示一次查几条记录。返回一个list对象(该list对象可以是 一个记录集,也可以是一个POJO类对象) (2)、publicintgetCount(),查询该表中的记录总数,返回一个int对象。 (3)、publicvoidclose(),放置所有关闭操作的方法。 3、调用页面,必须添加PageListener******,即实现addPageListener(Object)方法,参数为操作 数据库类的对象。 4、用getRecord()方法获取存有记录的list对象; 用getFirstPage()方法获取'首页'的标记; 用getPageUp()方法获取'上一页'的标记; 用getPageDown()方法获取'下一页'的标记; 用getLastPage()方法获取'末页'的标记; 用getPageForward()方法获取'跳转到第几页'的输入框标记; 用getCountRecord()方法获取总记录数; 用getCountPage()方法获取总页数; 用getCurrentPage()方法获取当前页数; 5、如果需要把上一页,下一页等标记换成图片,则只需调用 setPageDown('图片路径+图片名'), setPageUp('图片路径+图片名'), setFirstPage('图片路径+图片名'), setLastPage('图片路径+图片名'); 详细操作请查看帮助文档和具体实现案例; PageControlor分页插件(次插件仅支持jsp) 包含3个文件: PageControlor分页插件; 分页的帮助文档; 分页插件使用案例; 运行使用具体案例时,须注意以下几点: 1、运行环境为jdk(1.4以上),Tomcat(5.0以上),mysql(5.0.x); 2、运行时须改动init.properties,把数据库名,用户名和密码改称自己数据库的设置; 3、将news.sql文件导入到您的mysql服务器里面。 开发者:千里web架构实验室成员--刘捷 2007年10月29日
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值