一、解决的问题:
实现多条数据在jsp中的分页。
二、实现步骤:
1, 先看一下效果图:
2, 主要实现逻辑:如图所示,主要有两种分页的方式。
(1), 第一个相对简单一些,第二个原理一样,只是将'上一页', '下一页' 等变成了页码。
(2), 分页的主要逻辑由PageBean这个类来完成,先看一下代码:
PageBean.java,
在这个类中主要定义了分页的基本属性
public class PageBean {
private List records;//某页的数据
private int currentPage;//当前页
private int totalRecordsSize;//总共多少条记录
private int pageSize;//总共多少页
private int firstPage = 1;//首页
private int lastPage;//末页
private int pre;//上一页
private int next;//下一页
/**显示页码**/
private int beginPage;//第一个显示的页 码
private int endPage;//最后一个显示的页 码
public PageBean(List records, int currentPage, int pageSize, int totalRecordsSize) {
this.records = records;
this.currentPage = currentPage;
this.totalRecordsSize = totalRecordsSize;
this.pageSize = pageSize;
lastPage = (totalRecordsSize + pageSize - 1) / pageSize;//计算最后一页
pre = currentPage-1<=0?1:(currentPage-1);//计算上一页
next = currentPage+1>lastPage?lastPage:currentPage+1;//计算下一页
/**计算开始页码与结束页码**/
if(lastPage<=10){//如果页码不足10个,则全显示
beginPage = 1;
endPage = lastPage;
}else{//如果页码大于10个,
beginPage = currentPage - 4;//第一个显示的页码为当前页往前4个
endPage = currentPage + 5;////最后一个显示的页码为当前页往后5个
if(beginPage<1){//当前页往前不足4个,则显示前10个
beginPage = 1;
endPage = 10;
}else if(endPage>lastPage){ //如果最后个显示的页码大于最后一个页码(总页码),
endPage = lastPage;//最后一个页码为总页码
beginPage = endPage-10+1; //第一个页码为最后一个页码向前数10个
}
}
}
UserService.java
在这个类中,根据传入的currentPage算出查询sql中的limit x, y值。然后将查询出的结果封装到PageBean.java中的list属性内, pageBean需要四个参数分别为:
查询出的数据集合(users),当前页(currentPage),每页显示多少条(pageSize)及一共多少条(totalPageSize)
public class UserService {
public PageBean getUsers(int currentPage) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
List<User> users = new ArrayList<User>();
int totalPageSize=0;
int pageSize = 10;//默认为每页显示10条记录
try {
conn = jdbcutil.getConnection();
st = conn.createStatement();
rs = st.executeQuery("select count(id) totalNum from users");
if(rs.next()){
totalPageSize = rs.getInt("totalNum");
}
rs = null;
rs = st.executeQuery("select * from users limit "+(currentPage-1)*pageSize+","+ pageSize);
while (rs.next()) {
users.add(new User(rs.getInt(1),rs.getString(2)));
System.out.println(rs.getObject(1) + "\t" + rs.getObject(2) + "\t");
}
} catch (Exception e) {
e.printStackTrace();
}
PageBean page = new PageBean(users, currentPage, pageSize, totalPageSize);
return page;
}
}
UserServlet .java
调用userService的方法,并将封装了list的pageBean放在request域内.
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserService service = new UserService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String currentPage = request.getParameter("currentPage");
PageBean page = service.getUsers(Integer.valueOf(currentPage));
request.setAttribute("page", page);
request.getRequestDispatcher("/users.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
users.jsp
在这个页面中将查询出的数据展现,并显示分好的页数,及可操作的页面跳转链接如:‘首页’,‘下一页’等,并提供可提供的页面跳转(输入值须为数字,没做限制)。
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!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">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<style type="text/css">
table#border {
border-top: #000 1px solid;
border-left: #000 1px solid;
}
table#border td {
border-bottom: #000 1px solid;
border-right: #000 1px solid;
}
table#border th {
border-bottom: #000 1px solid;
border-right: #000 1px solid;
}
table#border tr{
background: GhostWhite;
}
table#border tr:nth-child(2n){
background: Lavender;
}
table#border tr{
background-color: expression((this.sectionRowIndex % 2 == 0) ? "GhostWhite" : "Lavender" );
}
</style>
<script type="text/javascript">
function toPage(page){
window.location = 'http://localhost:8080/pageDemo/userServlet?currentPage='+page;
}
function toPage2(page){
var page = document.getElementById("page");
window.location = 'http://localhost:8080/pageDemo/userServlet?currentPage='+page.value;
}
</script>
<title></title>
</head>
<body>
<center>
<br><br>
<h2>用户列表</h2>
<table id="border" border="0" cellspacing="0" width="60%" cellspacing="2" cellpadding="2" >
<tr style="background-color: Honeydew">
<th>序号</th>
<th>姓名</th>
</tr>
<c:forEach items="${page.records}" var="user">
<tr>
<td>${user.id }</td>
<td>${user.name }</td>
</tr>
</c:forEach>
</table>
<table>
<tr>
<td><a href="#" onclick="toPage(${page.firstPage})">首页</a></td>
<td><a href="#" onclick="toPage(${page.pre})">上一页</a></td>
<td><a href="#" onclick="toPage(${page.next})">下一页</a></td>
<td><a href="#" onclick="toPage(${page.lastPage})">末页</a></td>
<td>
<input id="page" type="text" size="2"/>
<input type="button" value="go" onclick="toPage2()"/>
</td>
<td>${page.currentPage}/${page.lastPage}, 共${page.totalRecordsSize}条, </td>
<c:forEach begin="${page.beginPage}" end="${page.endPage}" var="pageNum">
<c:if test="${pageNum == page.currentPage}">
<td><a href="#" onclick="toPage(${pageNum})"><font color="red">[${pageNum}]</font></a></td>
</c:if>
<c:if test="${pageNum != page.currentPage}">
<td><a href="#" onclick="toPage(${pageNum})"><font color="blue">[${pageNum}]</font></a></td>
</c:if>
</c:forEach>
</tr>
</table>
</center>
</body>
</html>
jdbcutil.java
连接数据库
public final class jdbcutil {
private static String url = "jdbc:mysql://localhost:3306/test";
private static String user = "root";
private static String password = "";
private jdbcutil(){
}
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(url,user,password);
}
public static void free(ResultSet rs,Statement st, Connection conn) throws SQLException{
try {
if(rs!=null)
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
if(st!=null)
st.close();
}catch(SQLException e){
e.printStackTrace();
}finally{
if(conn!=null)
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
}
User.java
封装类
package com.neoware.model;
public class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<<完>>
本文介绍了一种在JSP中实现多条数据分页的方法,包括PageBean类的设计与使用,UserService类中SQL查询与结果封装的过程,以及UserServlet如何处理请求并将数据传递给JSP页面进行展示。
2282

被折叠的 条评论
为什么被折叠?



