手动分页之后端分页
步骤分析
背景:对Emplee进行分页,选出生日再1990年以后出生的
1.定义实体类:
Employee
import java.util.Date;
public class Employee {
private int id;
private String name;
private Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public void setName(String name) {
this.name = name;
}
public Employee(int id, String name, Date birthday) {
this.id = id;
this.name = name;
this.birthday = birthday;
}
public Employee(Date birthday) {
this.birthday = birthday;
}
public Employee() {
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", birthday='" + birthday + '\'' +
'}';
}
}
2.创建pageBean对象,将查询的Employee对象全部放到pageBean中,以pageBean的方式进行返回
import java.util.List;
public class PageBean<Employee> {
private String currentPage;//当前页
private String pageSize;//每页条数
private Integer totalCount;//总条数
private Integer totalPage;//总页数
private List<Employee> list;//当前页数据
public String getCurrentPage() {
return currentPage;
}
public void setCurrentPage(String currPage) {
this.currentPage = currPage;
}
public String getPageSize() {
return pageSize;
}
public void setPageSize(String pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public List<Employee> getList() {
return list;
}
public void setList(List<Employee> list) {
this.list = list;
}
@Override
public String toString() {
return "PageBean{" +
"currentPage='" + currentPage + '\'' +
", pageSize='" + pageSize + '\'' +
", totalCount=" + totalCount +
", totalPage=" + totalPage +
", list=" + list +
'}';
}
}
3.编写前端页面,前端页面需要传入的参数就两个一个是当前页,一个是每页显示的数据条数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-3.3.1.min.js"></script>
</head>
<body>
<table >
</table>
<input type="button" id="prePage" value="上一页" >
<input type="button" id="nextPage" value="下一页" >
当前:<span id="currentPage"> </span>页
共<span id="totalPage"> </span>页
共 <span id="total"></span>条记录
</body>
<script>
var temp=0
$(function () {
$.ajax({
url:"/EmployeeListServlet",
type: "GET",
data: {"currentPage": 1,"pageSize":10},
datatype:"json",
success: function (data){
temp=data.currentPage
$("table").after("<tr id='t1'><th>id:</th><th>姓名:</th><th>生日:</th></tr>")
for(var i=0;i<data.list.length;i++){
$("#t1").after("<tr><th>"+data.list[i].id+"</th><th>"+data.list[i].name+"</th><th>"+data.list[i].birthday+"</th></tr>")
}
$("#currentPage").text(data.currentPage)
$("#totalPage").text(data.totalPage)
$("#total").text(data.totalCount)
}
})
});
$("#prePage").click(function () {
$.ajax({
url:"/EmployeeListServlet",
type: "POST",
data: {"currentPage": --temp,"pageSize":10},
success: function (data) {
$("tr").empty()
$("table").after("<tr id='t1'><th>id:</th><th>姓名:</th><th>生日:</th></tr>")
for(var i=0;i<data.list.length;i++){
$("#t1").after("<tr><th>"+data.list[i].id+"</th><th>"+data.list[i].name+"</th><th>"+data.list[i].birthday+"</th></tr>")
}
$("#currentPage").text(data.currentPage)
$("#totalPage").text(data.totalPage)
$("#total").text(data.totalCount)
}
})
})
$("#nextPage").click(function () {
$.ajax({
url:"/EmployeeListServlet",
type: "POST",
data: {"currentPage": ++temp,"pageSize":10},
success: function (data) {
$("tr").empty()
$("table").after("<tr id='t1'><th>id:</th><th>姓名:</th><th>生日:</th></tr>")
for(var i=0;i<data.list.length;i++){
$("#t1").after("<tr><th>"+data.list[i].id+"</th><th>"+data.list[i].name+"</th><th>"+data.list[i].birthday+"</th></tr>")
}
$("#currentPage").text(data.currentPage)
$("#totalPage").text(data.totalPage)
$("#total").text(data.totalCount)
}
})
})
</script>
</html>
4.编写Servlet,获取传递过来的参数,调用service层的方法
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
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 java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@WebServlet("/EmployeeListServlet")
public class EmployeeListServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json;charset=utf-8");
String currentPage=request.getParameter("currentPage");
String pageSize = request.getParameter("pageSize");
//对当前页和每页显示的大小进行判断,如果为空,则给个默认值
if(" ".equals(currentPage)){
currentPage="1";
}
if(" ".equals(pageSize)){
pageSize="10";
}
EmployeeService employeeService=new EmployeeService();
PageBean pageBean=employeeService.findEmpByPage(currentPage,pageSize);
ObjectMapper mapper=new ObjectMapper();
String data = mapper.writeValueAsString(pageBean);
System.out.println(data);
response.getWriter().write(data);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
5.Service层逻辑处理
import java.util.List;
import java.util.Map;
public class EmployeeService {
public PageBean findEmpByPage(String _currentPage, String _pageSize){
int currentPage=Integer.parseInt(_currentPage);
int pageSize=Integer.parseInt(_pageSize);
PageBean pageBean=new PageBean();
if(currentPage<=0){ //当前页小于0,则设置为1
currentPage=1;
}
pageBean.setPageSize(_pageSize);
//总记录数 总页数
Employeedao employeedao=new Employeedao();
int total=employeedao.getTotal();
pageBean.setTotalCount(total);
int totalPage = total%pageSize==0 ? total/pageSize:(total/pageSize)+1;
if(currentPage>=totalPage){
currentPage=totalPage;
}
pageBean.setCurrentPage(String.valueOf(currentPage));
pageBean.setTotalPage(totalPage);
//分页的数据集合
int startPage=(currentPage-1)*pageSize;
List<Employee> employees = employeedao.getPage(startPage, pageSize);
pageBean.setList(employees);
return pageBean;
}
public List<Employee> getAll(){
Employeedao employeedao=new Employeedao();
return employeedao.getAll();
}
}
6.Dao层查询数据库
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Employeedao {
//查询总记录数
public int getTotal(){
int total=0;
PreparedStatement pstmt=null;
ResultSet result=null;
JDBCUtils jdbc=new JDBCUtils();
Connection conn=jdbc.connect();
String sql="SELECT COUNT(*) from tbl_employee WHERE birthday>'1990-01-01'";
try {
pstmt = conn.prepareStatement(sql);
result = pstmt.executeQuery();
while (result.next()) {
total = result.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
jdbc.close(conn, pstmt, result);
}
return total;
}
//分页查询用户数
public List<Employee> getPage(int currentPage,int pageSize){
List<Employee> list=new ArrayList<Employee>();
PreparedStatement pstmt=null;
ResultSet result=null;
JDBCUtils jdbc=new JDBCUtils();
Connection conn=jdbc.connect();
try {
String sql="SELECT * from tbl_employee WHERE birthday>'1990-01-01' LIMIT ?,?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,currentPage);
pstmt.setInt(2,pageSize);
result = pstmt.executeQuery();
while (result.next()){
Employee employee = new Employee();
employee.setId(result.getInt(1));
employee.setName(result.getString(2));
employee.setBirthday(result.getDate(3));
list.add(employee);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
jdbc.close(conn, pstmt, result);
}
return list;
}
}
7.工具类
import java.sql.*;
public class JDBCUtils {
private Connection conn=null;
private PreparedStatement pstmt=null;
/**
* connect 连接数据库
* @return
*/
public Connection connect(){
String user="root";
String password="1234";
String driverClass = "com.mysql.jdbc.Driver";
String jdbcUrl = "jdbc:mysql://localhost:3306/demo";
try {
Class.forName(driverClass);
conn = DriverManager.getConnection(jdbcUrl, user, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
/**
* close 关闭数据库
* @param conn
* @param pstmt
*
*/
public void close(Connection conn,PreparedStatement pstmt,ResultSet result){
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
}
}
if(pstmt != null){
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(result != null){
try {
result.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}