在现实应用中,一个数据库的表中都会存储有大量的数据记录,如果一次将所有数据读取出来,除了浪费服务器资源外,对于用户阅也是不太友好的体验。所以我们使用分页将大量记录分成多个部分,允许用户仅显示一部分数据记录。 在一个页面中加载所有记录可能需要时间,因此建议创建或使用分页。在servlet中,我们可以轻松地开发分页示例。
在这个servlet分页示例中,使用MySQL数据库来获取记录。
在这里,“testdb”
数据库中创建了“employees”
表。“employees”
表有以下几个字段:id
,name
,age
,education
,address
和salary
。创建表和手动插入记录或导入本示例提供的SQL文件。
DROP TABLE IF EXISTS `employees`;
CREATE TABLE `employees` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL DEFAULT '',
`age` int(3) unsigned NOT NULL DEFAULT '0',
`education` varchar(32) DEFAULT '' COMMENT '学历',
`address` varchar(254) DEFAULT NULL,
`salary` float(8,2) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of employees
-- ----------------------------
INSERT INTO `employees` VALUES ('1', '李小春', '23', '其它', '海口市人民大道1800号', '8900.00');
INSERT INTO `employees` VALUES ('2', '张辉', '28', '本科', '广州天河区珠村市场', '15800.98');
INSERT INTO `employees` VALUES ('3', '林贤弟', '29', '博士', '广州白云区龙塘村120号', '18990.99');
INSERT INTO `employees` VALUES ('4', '王小简', '23', '本科', '海口人民大道1688号', '899.98');
INSERT INTO `employees` VALUES ('5', '蔡世杰', '27', '专科', '上海市宝山区联杨路2211弄26号', '15800.00');
INSERT INTO `employees` VALUES ('6', '张承龙', '30', '本科', '上海市虹口区虬江路522号', '23000.00');
INSERT INTO `employees` VALUES ('7', '李林奕', '26', '本科', '上海市徐汇区漕宝路440号', '32600.00');
INSERT INTO `employees` VALUES ('8', '刘皓轩', '28', '研究生', '上海松江九亭立同商务广场', '29000.00');
INSERT INTO `employees` VALUES ('9', '周佳豪', '36', '博士', '深圳市宝安区沙井街道办107国道富达工业区B栋', '48000.00');
INSERT INTO `employees` VALUES ('10', '陈聪', '23', '本科', '福田区文蔚大厦19层', '9800.00');
打开Eclipse,创建一个动态Web项目:ServletPagination,其完整的目录结构如下所示 -
以下是这个项目中的几个主要的代码文件。
文件:index.html -
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Servlet分页示例</title>
</head>
<body>
<div style="text-align: center;">
<a href="ViewServlet">点击查看分页效果</a>
</div>
</body>
</html>
文件:Emp.java -
package com.yiibai.bean;
public class Emp {
private int id;
private String name;
private int age;
private String address;
private String education;
private float salary;
public int getId() {
return id;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public void setId(int id) {
this.id = id;
}
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
文件:EmpDao.java -
package com.yiibai.dao;
import com.yiibai.bean.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class EmpDao {
public static Connection getConnection() {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/testdb?useSSL=false&characterEncoding=utf8",
"root", "123456");
} catch (Exception e) {
System.out.println(e);
}
return con;
}
public static List<Emp> getRecords(int page, int pageSize) {
List<Emp> list = new ArrayList<Emp>();
int start = 0;
if (page > 0) {
start = (page - 1) * pageSize;
}
try {
Connection con = getConnection();
String sql = "SELECT * FROM employees ORDER BY id LIMIT " + start + "," + pageSize;
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Emp e = new Emp();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getFloat("salary"));
list.add(e);
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
return list;
}
// 表中的记录总数
public static int getTotal() {
try {
Connection con = getConnection();
PreparedStatement ps = con.prepareStatement("SELECT count(*) AS total FROM employees ");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
return rs.getInt("total");
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
return 0;
}
// 总页数
public static int totalPages(int pageSize) {
int total = getTotal();
int totalPages = (total % pageSize == 0) ? (total / pageSize) : (total / pageSize) + 1;
return totalPages;
}
}
文件:ViewServlet.java -
package com.yiibai;
import java.io.IOException;
import java.io.PrintWriter;
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.yiibai.bean.Emp;
import com.yiibai.dao.EmpDao;
@WebServlet("/ViewServlet")
public class ViewServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
// 每页3条记录
int pageSize = 3;
String spage = request.getParameter("page");
if (spage == null || spage == "") {
spage = "1";
}
int page = Integer.parseInt(spage);
int totalPage = EmpDao.totalPages(pageSize);
List<Emp> list = EmpDao.getRecords(page, pageSize);
out.print("<h1>当前第: " + spage + "/" + totalPage + " 页</h1>");
out.print("<table border='1' cellpadding='4' width='60%'>");
out.print("<tr><th>编号</th><th>姓名</th><th>薪水</th>");
for (Emp e : list) {
out.print("<tr><td>" + e.getId() + "</td><td>" + e.getName() + "</td><td>" + e.getSalary() + "</td></tr>");
}
out.print("</table>");
out.print("<a href='ViewServlet?page=1'>首页</a> ");
for (int i = 1; i <= totalPage; i++) {
out.print("<a href='ViewServlet?page=" + i + "'>" + i + "</a> ");
}
out.print("<a href='ViewServlet?page=" + totalPage + "'>最后一页</a> ");
out.close();
}
}
注意:此项目使用
@WebServlet("ServletURL")
来映射URL,因此不需要配置web.xml
。
在编写上面代码后,部署此Web应用程序(在项目名称上点击右键->”Run On Server…”),打开浏览器访问URL: http://localhost:8080/ServletPagination/ ,如果没有错误,应该会看到以下结果 -
点击链接,进入分页页面 -
分别点击第1
,2
,3
,4
页,结果如下所示 -
第1
,2
,3
,4
页所执行的SQL语句分别如下:
SELECT * FROM employees ORDER BY id LIMIT 0,3
SELECT * FROM employees ORDER BY id LIMIT 3,3
SELECT * FROM employees ORDER BY id LIMIT 6,3
SELECT * FROM employees ORDER BY id LIMIT 9,3