直接上結構圖(如果你在寫的時候碰見一些沒見過的方法名,請參考我的工具類 也就是7 DButil)
- edu.ahau.bean
這是Page實體類,這裏面封裝了我們將在servlet裏面需要用的參數
public class Page {
// 當前頁 currentPage
private int currentPage ;
// 頁面大小 pageSize
private int pageSize ;
// 總數據 totalCount
private int totalCount;
// 總頁數 totalPage
private int totalPage ;
// 當前頁的數據集合 students
private List<Student> students;
public Page() {
}
public Page(int currentPage, int pageSize, int totalCount, int totalPage, List<Student> students) {
this.currentPage = currentPage;
this.pageSize = pageSize;
this.totalCount = totalCount;
this.totalPage = totalPage;
this.students = students;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
/*
* 總頁數 = 數據總數%頁面大小==0? 數據總數/頁面大小:數據總數/頁面大小+1 ;
*
* 當我們調換用了 數據總數的set() 和 頁面大小的set()以後,自動計算出 總頁數
* 務必注意順序:先set 數據總數 再set 頁面大小
*/
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
//自動計算出 總頁數
// 總頁數 = 數據總數%頁面大小==0? 數據總數/頁面大小:數據總數/頁面大小+1 ;
this.totalPage =this.totalCount%this.pageSize==0?this.totalCount/this.pageSize:totalCount/this.pageSize+1;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
return totalPage;
}
//給總頁數賦值
// public void setTotalPage(int totalPage) {
// this.totalPage = totalPage;
// }
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
@Override
public String toString() {
return "Page [currentPage=" + currentPage + ", pageSize=" + pageSize + ", totalCount=" + totalCount
+ ", totalPage=" + totalPage + ", students=" + students + "]";
}
}
下面的是Student實體類
public class Student {
private String stuName;
private int age;
private int id;
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public Student() {
super();
}
public Student(String stuName, int age ,int id) {
super();
this.id = id;
this.stuName = stuName;
this.age = age;
}
@Override
public String toString() {
return "Student [stuName=" + stuName + ", age=" + age + ", id=" + id + "]";
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
對持久層我無話可說 都是可以看的懂的東西,唯一的就是我們在寫sql的時候需要用的between and查詢
- edu.ahau.dao
public interface IStudenetDAO {
List<Student> queryStudentsByPage(int currentPage, int pageSize);
int getTotalCount();//查詢總數
}
- edu.ahau.dao.impl
public class StudentDaoImpl implements IStudenetDAO{
@Override
public List<Student> queryStudentsByPage(int currentPage, int pageSize) {
String sql = " select * from student where id between ? and ?";
Object[] params = {(currentPage-1)*pageSize+1,currentPage*pageSize};
List<Student> students = new ArrayList<>();
ResultSet rs = DBUtil.executeQuery(sql, params) ;
try {
while(rs.next()) {
Student student = new Student(rs.getString("sname"),rs.getInt("sage"), rs.getInt("id")) ;
students.add(student) ;
}
} catch (SQLException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}finally {
DBUtil.closeAll(rs, null, null);
}
return students;
}
@Override
public int getTotalCount() {
// TODO Auto-generated method stub
String sql = "select count(1) from student";
return DBUtil.getTotalCount(sql);
}
}
- edu.ahau.service
public interface IStudentService {
List<Student> queryStudentsByPage(int currentPage ,int pageSize);
public int getTotalCount();
}
- edu.ahau.service.impl
public class StudentServiceImpl implements IStudentService {
StudentDaoImpl studentDao = new StudentDaoImpl();
@Override
public List<Student> queryStudentsByPage(int currentPage, int pageSize) {
// TODO Auto-generated method stub
return studentDao.queryStudentsByPage(currentPage, pageSize);
}
@Override
public int getTotalCount() {
// TODO Auto-generated method stub
return studentDao.getTotalCount();
}
}
- edu.ahau.servlet
從page類中的
setPageSize()
裏面我們可以知道在servlet裏面獲取數據的時候一定要將我們得到的數據總是放在頁面大小的前面(即頁面數據量)
/**
* Servlet implementation class QueryStudentByPage
*/
@WebServlet("/QueryStudentByPage")
public class QueryStudentByPage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public QueryStudentByPage() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
Page page = new Page();
IStudentService studentService = new StudentServiceImpl();
String cPage = request.getParameter("currentPage");
System.out.println(cPage);
int pageSize = 3;
//默認得到第一頁
if (cPage==null||cPage=="0") {
cPage = "1";
}
int currentPage =Integer.parseInt(cPage);
page.setCurrentPage(currentPage);
int count = studentService.getTotalCount();//數據總數
page.setTotalCount(count);
page.setPageSize(pageSize);
List<Student> students = studentService.queryStudentsByPage(currentPage, pageSize);
page.setStudents(students);
request.setAttribute("p", page);
System.out.println(page);
System.out.println(page.getCurrentPage());
request.getRequestDispatcher("index.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
- edu.ahau.util
public class DBUtil {
static String url = "jdbc:mysql://localhost:3306/page?useUnicode=true&useJDBCCompliantTimezo"
+ "neShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
static String user = "root";
static String password = "123";
static PreparedStatement pstmt;
static Connection connection;
static ResultSet rs;
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver") ;
return DriverManager.getConnection( url,user,password ) ;
}
public static void closeAll(ResultSet rs,Statement stmt,Connection connection)
{
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
if(connection!=null)connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//查詢總數
public static int getTotalCount(String sql) {
int count = -1;
try {
pstmt = createPreParedStatement(sql, null);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
count = rs.getInt(1);
}
} catch (Exception e) {
// TODO: handle exception
}finally {
closeAll(rs, pstmt, connection);
}
return count;
}
public static PreparedStatement createPreParedStatement(String sql,Object[] params) throws ClassNotFoundException, SQLException {
pstmt = getConnection() .prepareStatement( sql) ;
if(params!=null ) {
for(int i=0;i<params.length;i++) {
pstmt.setObject(i+1, params[i]);
}
}
return pstmt;
}
public static ResultSet executeQuery( String sql ,Object[] params) {
Student student = null;
List<Student> students = new ArrayList<>();
try {
pstmt = createPreParedStatement(sql,params);
rs = pstmt.executeQuery() ;
return rs ;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null ;
} catch (SQLException e) {
e.printStackTrace();
return null ;
}catch (Exception e) {
e.printStackTrace();
return null ;
}
}
}
下面的是jsp代碼,僅供參考的頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="edu.ahau.bean.*"%>
<%@page import="java.util.List"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table border="1px">
<tr>
<th>學號</th>
<th>姓名</th>
<th>年齡</th>
</tr>
<%
//獲取request域中的數據
Page p = (Page)request.getAttribute("p");
for (Student student : p.getStudents()) {
%>
<tr>
<td><%=student.getId() %> </a>
</td>
<td><%=student.getStuName() %> </td>
<td><%=student.getAge() %> </td>
</td>
</tr>
<%
}
%>
</table>
<a href="QueryStudentByPage?currentPage=1">首頁</a>
<a href="QueryStudentByPage?currentPage=<%=p.getCurrentPage()-1%>">上一頁</a>
<a href="QueryStudentByPage?currentPage=<%=p.getCurrentPage()+1%>">下一頁</a>
</body>
</html>
思路源自於: 嗶哩嗶哩顏羣老師