Servlet_Mysql_JDBC实现分页技术

分页几个必要 的参数: 

每页需要显示多少条数据,

总的 数据记录数,

当前是第几页,

总页数,

	/**每页多少条数据*/
	private int pageSize = 10;
	/**总记录条数*/
	private int totalCount;   
	/**当前页*/
	private int currentPage;
	/**总页数*/
	private int pageCount;


必要的方法:

计算总页数 总记录数除以每页显示的记录数 然后总记录数对每页显示的记录进行取余 如果余数是0那么总页数就是 前面的 余数 ,如果不等于0余数就要+1 +1后的余数就是总页数为了使代码更健壮,在取到总页数应该加一个判断,如果余数是0那么余数就应该设置为1(不可能页面 一页也没有什么都不显示)

/**
	 * 计算总页数
	 * @return
	 */
	public int getPageCount() {
		pageCount = totalCount / pageSize;  // 26  /  10     2   
		int mod = totalCount % pageSize;    // 26  %  10     6   
		if (mod != 0) {
			pageCount++;   //3
		}
		return totalCount == 0 ? 1 : pageCount;
	}

获取开始记录序号

/**
	 *  获取开始记录序号
	 *  
	 *  每页显示10条记录
	 *  1页   0    0-9  
	 *  2页   10   10-19      
	 *  3页   20    20-29
	 *    .....
	 *  n页    (n-1)*10
	 *    
	 */
	public int getFromIndex() {
		return (currentPage - 1) * pageSize;
	}

获取结束记录序号

	/**
	 * 结束记录序号
	 * @return
	 */
	public int getToIndex() {
		return Math.min(totalCount, currentPage * pageSize);
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

PageUtil.java

package com.yzk.paging.util;

public class PageUtil {
	/**每页多少条数据*/
	private int pageSize = 10;
	/**总记录条数*/
	private int totalCount;   
	/**当前页*/
	private int currentPage;
	/**总页数*/
	private int pageCount;

	public PageUtil(int pageSize, int totalCount, int currentPage) {
		this.pageSize = pageSize;
		this.totalCount = totalCount;
		this.setCurrentPage(currentPage);
	}
	
	/**
	 * 当前页边界检查
	 * 不大不大于总页数,最小不小于一页
	 * @param currentPage
	 */
	public void setCurrentPage(int currentPage) {
		int activePage = currentPage <= 0 ? 1 : currentPage;
		activePage = activePage > getPageCount() ? getPageCount() : activePage;
		this.currentPage = activePage;
	}

	/**
	 * 计算总页数
	 * @return
	 */
	public int getPageCount() {
		pageCount = totalCount / pageSize;  // 26  /  10     2   
		int mod = totalCount % pageSize;    // 26  %  10     6   
		if (mod != 0) {
			pageCount++;   //3
		}
		return totalCount == 0 ? 1 : pageCount;
	}

	/**
	 *  获取开始记录序号
	 *  
	 *  每页显示10条记录
	 *  1页   0    0-9  
	 *  2页   10   10-19      
	 *  3页   20    20-29
	 *    .....
	 *  n页    (n-1)*10
	 *    
	 */
	public int getFromIndex() {
		return (currentPage - 1) * pageSize;
	}

	/**
	 * 结束记录序号
	 * @return
	 */
	public int getToIndex() {
		return Math.min(totalCount, currentPage * pageSize);
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
}


UserDao.Java

select * from  user limit 开始,结束;

package com.yzk.paging.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.yzk.paging.model.User;

public class UserDao {
	public static List<User> getPageUtilsUserLists(int first, int max) {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		String url = "jdbc:mysql://localhost:3306/CarSystem";
		String user = "root";
		String password = "root";

		List<User> lists = new ArrayList<User>();
		Connection connection = null;
		PreparedStatement ps = null;
		try {
			connection = DriverManager.getConnection(url, user, password);
			ps = connection.prepareStatement("select * from user limit ?,?");
			ps.setInt(1, first);
			ps.setInt(2, max);
			ResultSet rs = ps.executeQuery();

			while (rs.next()) {
				User u = new User();
				u.setId(rs.getInt("id"));
				u.setUsername(rs.getString("username"));
				u.setPassword(rs.getString("password"));
				lists.add(u);
			}

			return lists;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (connection != null) {
					connection.close();
				}
				if (ps != null) {
					ps.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}

		return lists;
	}

	 public static void main(String[] args) {
	
	 System.out.println(totalCount());
	 }
	public static int totalCount() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		String url = "jdbc:mysql://localhost:3306/CarSystem";
		String user = "root";
		String password = "root";
		Connection connection = null;
		PreparedStatement ps = null;
		try {
			connection = DriverManager.getConnection(url, user, password);
			ps = connection.prepareStatement("select *  from user");
			ResultSet rs = ps.executeQuery();
			int i = 0;
			while (rs.next()) {
				i++;
			}
			return i;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (connection != null) {
					connection.close();
				}
				if (ps != null) {
					ps.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}
		return 0;
	}
}

PageServlet.java
package com.yzk.paging.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yzk.paging.dao.UserDao;
import com.yzk.paging.model.User;
import com.yzk.paging.util.PageUtil;

@SuppressWarnings("serial")
@WebServlet({ "/PagerServlet", "/pagerservlet.servlet" })
public class PagerServlet extends HttpServlet {
	private UserDao userDao = new UserDao();
	private int currentPage = 1;

	@SuppressWarnings("static-access")
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String pageNum = request.getParameter("pageNum");
		if (pageNum != null && !"".equals(pageNum)) {
			currentPage = Integer.parseInt(pageNum);
		}

		PageUtil pageUtil = new PageUtil(10, userDao.totalCount(), currentPage);

		List<User> lists = userDao.getPageUtilsUserLists(pageUtil.getFromIndex(), pageUtil.getPageSize());
		request.setAttribute("userLists", lists);
		request.setAttribute("currentPage", currentPage);
		request.setAttribute("totalPage", pageUtil.getPageCount());

		request.getRequestDispatcher("list_user_pager.jsp").forward(request, response);

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

list_user_pager.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户列表</title>
<%
	// 获取请求的上下文
	String context = request.getContextPath();
%>
<script type="text/javascript">
// 当前第几页数据
var currentPage = ${currentPage};

// 总页数
var totalPage = ${totalPage};

function submitForm(actionUrl){
	window.location.href = actionUrl;
}

// 第一页
function firstPage(){
	if(currentPage == 1){
		alert("已经是第一页数据");
		return false;
	}else{
		submitForm("<%=context%>/pagerservlet.servlet?pageNum=1");
		return true;
	}
}

// 下一页
function nextPage(){
	if(currentPage == totalPage){
		alert("已经是最后一页数据");
		return false;
	}else{
		submitForm("<%=context%>/pagerservlet.servlet?pageNum=" + (currentPage+1));
		return true;
	}
}

// 上一页
function previousPage(){
	if(currentPage == 1){
		alert("已经是第一页数据");
		return false;
	}else{
		submitForm("<%=context%>/pagerservlet.servlet?pageNum=" + (currentPage-1));
		return true;
	}
}

// 尾页
function lastPage(){
	if(currentPage == totalPage){
		return false;
	}else{
		submitForm("<%=context%>/pagerservlet.servlet?pageNum=${totalPage}");
			return true;
		}
	}
</script>
</head>
<body>
		<table width="100%" border="0" bgcolor="#cccccc">
			<tr>
				<td>ID</td>
				<td>用户名</td>
				<td>编号</td>
				<td colspan="2">操作</td>
			</tr>

			<%String color = ""; int c = 1;%>
			<c:forEach items="${userLists}" var="user">
				<%
					if (c == 1) { color = "#ffffff"; c = 0; } else {
					color = "#f5f5f5"; c = 1; }
				%>
				<tr bgcolor="<%=color%>">
					<td>${user.id}</td>
					<td>${user.username}</td>
					<td>${user.password}</td>
					<td>
						<a href="../user/delete.do?id=${user.id}">删除</a>
					</td>
					<td>
						<a
							href="../user/update.do?name=${user.username}">
							修改
						</a>
					</td>
				</tr>

			</c:forEach>
		</table>
	</element>
	<br>
	<br>共${totalPage }页  当前第${currentPage }页  
	<a href="#" οnclick="firstPage();">首页</a>
	<a href="#" οnclick="previousPage();">上一页</a>
	<a href="#" οnclick="nextPage();">下一页</a>
	<a href="#" οnclick="lastPage();">尾页</a>
</body>
</html>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

茅十八呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值