Javaweb 实现分页功能

package cn.zr.testpage.entity;

public class User {
    
    private String name;
    private int age;
    private String hobby;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getHobby() {
        return hobby;
    }
    public void setHobby(String hobby) {
        this.hobby = hobby;
    }
    public User() {
    }
    public User(String name, int age, String hobby) {
        this.name = name;
        this.age = age;
        this.hobby = hobby;
    }
    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + ", hobby=" + hobby + "]";
    }
    
    
    
}





package cn.zr.testpage.service;

import java.util.List;

import cn.zr.testpage.entity.User;
import cn.zr.testpage.utils.Page;

public interface UserService {

    /**
     * 获取总数量
     * @return 返回总数
     */
    int getAmount();

    /**
     * 获取当前页的数据
     * @param page 
     * @return 返回前页的数据
     */
    List<User> getUserInfo(Page page);

}






package cn.zr.testpage.service.impl;

import java.util.List;

import cn.zr.testpage.dao.UserDao;
import cn.zr.testpage.dao.impl.UserDaoImpl;
import cn.zr.testpage.entity.User;
import cn.zr.testpage.service.UserService;
import cn.zr.testpage.utils.Page;

public class UserServiceImpl implements UserService {
private UserDao userDao;
// 通过代码块加载实现类
{
userDao = new UserDaoImpl();
}

@Override
public int getAmount() {
return userDao.getAmount();
}

@Override
public List<User> getUserInfo(Page page) {
return userDao.getUserInfo(page);
}

}

package cn.zr.testpage.dao;

import java.util.List;

import cn.zr.testpage.entity.User;
import cn.zr.testpage.utils.Page;

public interface UserDao {

/**
* 获取总数量
* @return 返回总数
*/
int getAmount();

/**
* 获取当前页的数据
* @param page
* @return 返回前页的数据
*/
List<User> getUserInfo(Page page);

}

package cn.zr.testpage.dao.impl;


import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.zr.testpage.dao.UserDao;
import cn.zr.testpage.entity.User;
import cn.zr.testpage.utils.JdbcUtils;
import cn.zr.testpage.utils.Page;
import cn.zr.testpage.utils.UserBasicalImpl;

public class UserDaoImpl extends UserBasicalImpl implements UserDao{


/**
* 获取总数
*/
@Override
public int getAmount() {
connection = JdbcUtils.getConnection();
String sql = "SELECT COUNT(*) FROM USERINFO";
int count = 0;
try {
pStatement = connection.prepareStatement(sql);
rSet = pStatement.executeQuery();
if(rSet.next()){
count = rSet.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
// 调用父类方法关闭资源
super.close();
}
return count;
}

/**
* 获取当前页的数据
* @param page
* @return 返回前页的数据
*/
@Override
public List<User> getUserInfo(Page page) {

connection = JdbcUtils.getConnection();
//基于MySQL的函数的分页
String sql = "SELECT 姓名,年龄,爱好 FROM USERINFO LIMIT ?,?";
// 创建集合
List<User> list = new ArrayList<User>();
try {
pStatement = connection.prepareStatement(sql);
//设置相关参数
pStatement.setInt(1, page.getStart());
pStatement.setInt(2, page.getSize());
rSet = pStatement.executeQuery();
while(rSet.next()){
User user = new User();
user.setName(rSet.getString("姓名"));
user.setAge(rSet.getInt("年龄"));
user.setHobby(rSet.getString("爱好"));
list.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
// 调用父类方法关闭资源
super.close();
}
return list;
}

}

package cn.zr.testpage.servlet;

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

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

import cn.zr.testpage.entity.User;
import cn.zr.testpage.service.UserService;
import cn.zr.testpage.service.impl.UserServiceImpl;
import cn.zr.testpage.utils.BaseServlet;
import cn.zr.testpage.utils.Page;

public class ListServlet extends BaseServlet{

private static final long serialVersionUID = 1L;

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

System.out.println("...doGet...");

// 获取当前页
String curpage = req.getParameter("curpage");
UserService userService = new UserServiceImpl();
// 获取总数量
int count = userService.getAmount();
//字符串转成整型
int currentpage = super.currentPage(curpage);
// 创建page对象
Page page = new Page(count, currentpage, pagesize);
// 获取当前页的数据
List<User> users = userService.getUserInfo(page);
//将相关数据存储起来
req.setAttribute("page", page);
req.setAttribute("users", users);

System.out.println(count);
System.out.println(users);
//转发
req.getRequestDispatcher("/WEB-INF/jsp/list.jsp").forward(req, resp);



}


}

package cn.zr.testpage.utils;

import javax.servlet.http.HttpServlet;


public class BaseServlet extends HttpServlet {

public int pagesize = 2;


public int currentPage(String cpage){
int currentpage = cpage!=null && !"".equals(cpage) && isint(cpage)? currentpage=Integer.parseInt(cpage):1;
return currentpage;
}

public boolean isint(String str){
boolean bo = true;
try {
Integer.parseInt(str);
} catch (Exception e) {
bo = false;
}
return bo;
}

}

package cn.zr.testpage.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* @author lf
*
*/
public class JdbcUtils {

// 获取数据库连接
public static Connection getConnection() {
String url="jdbc:mysql://localhost:3306/test?allowMultiQueries=true&useUnicode=true&amp;characterEncoding=utf8";
String user="LF";
String password ="LF";
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}

return connection;
}
}

package cn.zr.testpage.utils;


public class Page {

// 页数(第几页)
private int currentpage;

// 查询数据库里面对应的数据有多少条
private int total;// 从数据库查处的总记录数

// 每页查询的数量条
private int size;

// 下页
private int next;

// 最后一页
private int last;

private int lpage;

private int rpage;

//从哪条开始查
private int start;

public Page() {
super();
}

public int getCurrentpage() {
return currentpage;
}

/****
*
* @param currentpage
* @param total
* @param pagesize
*/
public void setCurrentpage(int currentpage,int total,int pagesize) {
//如果整除表示正好分N页,如果不能整除在N页的基础上+1页
int totalPages = total%pagesize==0? total/pagesize : (total/pagesize)+1;

//总页数
this.last = totalPages;

//判断当前页是否越界,如果越界,我们就查最后一页
if(currentpage>totalPages){
this.currentpage = totalPages;
}else{
this.currentpage=currentpage;
}
if(currentpage<=0){
this.currentpage=1;
}

//计算start 1----0 2 ------ 5
this.start = (this.currentpage-1)*pagesize;

}

public int getTotal() {
return total;
}

public void setTotal(int total) {
this.total = total;
}

public int getSize() {
return size;
}

public void setSize(int size) {
this.size = size;
}

public int getNext() {
return currentpage<last? currentpage+1: last;
}


//上一页
public int getUpper() {
return currentpage>1? currentpage-1: currentpage;
}

public int getLast() {
return last;
}

//总共有多少页,即末页
public void setLast(int last) {
this.last = total%size==0? total/size : (total/size)+1;
}

public int getLpage() {
return lpage;
}

public void setLpage(int lpage) {
this.lpage = lpage;
}

public int getRpage() {
return rpage;
}

public void setRpage(int rpage) {
this.rpage = rpage;
}

/****
*
* @param total 总记录数
* @param currentpage 当前页
* @param pagesize 每页显示多少条
*/
public Page(int total,int currentpage,int pagesize) {
//总记录数
this.total = total;
//每页显示多少条
this.size=pagesize;

//计算当前页和数据库查询起始值以及总页数
setCurrentpage(currentpage, total, pagesize);

//分页计算
int leftcount =5, //需要向上一页执行多少次
rightcount =4;
//起点页
this.lpage =currentpage;
//结束页
this.rpage =currentpage;

//2点判断
this.lpage = currentpage-leftcount; //正常情况下的起点
this.rpage = currentpage+rightcount; //正常情况下的终点

//页差=总页数和结束页的差
int topdiv = this.last-rpage; //判断是否大于最大页数

/***
* 起点页
* 1、页差<0 起点页=起点页+页差值
* 2、页差>=0 起点和终点判断
*/
this.lpage=topdiv<0? this.lpage+topdiv:this.lpage;

/***
* 结束页
* 1、起点页<=0 结束页=|起点页|+1
* 2、起点页>0 结束页
*/
this.rpage=this.lpage<=0? this.rpage+(this.lpage*-1)+1: this.rpage;

/***
* 当起点页<=0 让起点页为第一页
* 否则不管
*/
this.lpage=this.lpage<=0? 1:this.lpage;

/***
* 如果结束页>总页数 结束页=总页数
* 否则不管
*/
this.rpage=this.rpage>last? this.last:this.rpage;
}


public int getStart() {
return start;
}

}

package cn.zr.testpage.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserBasicalImpl {

protected Connection connection;
protected PreparedStatement pStatement;
protected ResultSet rSet;

public void close(){
// 关闭资源
try {
if (rSet!=null) {
rSet.close();
}
if (pStatement!=null) {
pStatement.close();
}
if (connection!=null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>用户信息</title>

</head>

<body>

<table>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>爱好</th>
</tr>
<c:forEach items="${users }" var="user" varStatus="userindex">
<tr>
<td>${user.name }</td>
<td>${user.age }</td>
<td>${user.hobby }</td>
</tr>
</c:forEach>
</table>

<div>
<a href="?curpage=1">首页</a>
<c:forEach begin="${page.lpage}" end="${page.rpage}" var="pageNum">
<a href="?curpage=${pageNum }">${pageNum }</a>
</c:forEach>
<a href="?curpage=${page.last }">尾页</a>
</div>

</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<servlet>
<servlet-name>list</servlet-name> <!-- 名字随便 -->
<servlet-class>com.ltjs.servlet.ListServlet</servlet-class> <!-- servlet类名-->
</servlet>

<servlet-mapping>
<servlet-name>list</servlet-name>
<url-pattern>/list</url-pattern> <!-- url访问虚拟路径,最后我们就是通过工程名/login进行访问的,像这样http://127.0.0.1:8000/LoginAction/login-->
</servlet-mapping>

</web-app>

各位需要俩个jar包:

1、jstl-1.2.jar  2、mysql-connector-java-5.1.29.jar

原文地址:https://www.cnblogs.com/flywang/p/6610516.html