java分頁的寫法
阿新 • • 發佈:2018-12-31
第一步:
首先需要到如各部分歲對應的包,例如資料庫驅動的包,實體類的包,c3p0的包,以及c3p0的配置檔案
建立資料庫,建立資料庫所對應的一個實體類,例如:student類,裡邊包含私有的屬性,及set和get方法
第二步:
建立另一個關於分頁的實體類,裡邊只包含5項,如下可見
package com.qf.javabean; import java.util.List; public class PagStudent<T> { private int currentpage;//當前頁 private int pagsize;//每頁的資料量 private int totalpage;//總頁數 private int totalcount;//總資料量 private List<T> list; public synchronized int getCurrentpage() { return currentpage; } public synchronized void setCurrentpage(int currentpage) { this.currentpage = currentpage; } public synchronized int getPagsize() { return pagsize; } public synchronized void setPagsize(int pagsize) { this.pagsize = pagsize; } public synchronized int getTotalpage() { return (int)Math.ceil(totalcount*1.0/pagsize); } //記住需要刪除一個方法,是算出來的,不是被設定的 public synchronized int getTotalcount() { return totalcount; } public synchronized void setTotalcount(int totalcount) { this.totalcount = totalcount; } public synchronized List<T> getList() { return list; } public synchronized void setList(List<T> list) { this.list = list; } public PagStudent(int currentpage, int pagsize, int totalcount, List<T> list) { super(); this.currentpage = currentpage; this.pagsize = pagsize; this.totalcount = totalcount; this.list = list; } public PagStudent() { super(); } }
第三步:建立JSP頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'StudentPaging.jsp' starting page</title> <meta charset="UTF-8"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <!-- Student [id=1, name=張無懼, sex=null, age=0, password=null, qq=null, phone=null, major=null, grade=null] --> <body> <table border="1px" align="center" width="90%" cellspacing="0px"> <tr> <th colspan="9"><h1>學員資訊展示平臺</h1></th> </tr> <tr> <th >學員編號</th> <th >姓名</th> <th >性別</th> <th >年齡</th> <th >密碼</th> <th >QQ號</th> <th >手機號</th> <th >專業</th> <th >班級</th> </tr> <c:forEach items="${page.list }" var="it"> <!-- 屬性導航 --> <tr> <td>${it.id }</td> <td>${it.name }</td> <td>${it.sex }</td> <td>${it.age }</td> <td>${it.password }</td> <td>${it.qq }</td> <td>${it.phone }</td> <td>${it.major }</td> <td>${it.grade }</td> </tr> </c:forEach> </table> <center> <c:if test="${page.currentpage != 1 }"> <a href="${pageContext.request.contextPath }/servlet/PagStudent?currentpage=${page.currentpage-1 }">[上一頁]</a> </c:if> <!-- 表裡中間位置 ${page.totalpage }--> <c:forEach var="i" begin="1" end="${page.totalpage}" step="1"> <%-- <c:forEach var="i" begin="${i }" end="${(i+8)>page.totalpage?page.totalpage:(i+8) }" step="1"> --%> <!-- 當頁數過多時,顯示部分頁數,隨著頁數的增大,隱藏前邊頁數,顯示後邊的頁數 --> <c:if test="${page.currentpage == i }"> ${i } </c:if> <c:if test="${page.currentpage !=i }"> <a href="${pageContext.request.contextPath }/servlet/PagStudent?currentpage=${i }">${i }</a> </c:if> </c:forEach> <c:if test="${page.totalpage != page.currentpage }"> <a href="${pageContext.request.contextPath }/servlet/PagStudent?currentpage=${page.currentpage+1 }">[下一頁]</a> </c:if> <br/> 當前${page.currentpage }/總共${page.totalpage } </center> </body> </html>
第四步:建立servlet,裡邊包含(獲取資料,呼叫邏輯,轉發或重定向)
package com.qf.web; import java.io.IOException; import java.sql.SQLException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.qf.javabean.Student; import com.qf.service.StudentService; public class PagStudent extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); int currentpage = Integer.parseInt(request.getParameter("currentpage")); // 當第一次訪問的時候應該從請求中傳遞一個頁數 // System.out.println(currentpage+"獲取了資料"); int pagesize = 5;// 控制每頁顯示的資料量 try { com.qf.javabean.PagStudent<Student> pagStudent = new StudentService().findPage(currentpage, pagesize); request.getSession().setAttribute("page", pagStudent); System.out.println("我又回到了這個介面"); System.out.println(pagStudent.toString()); List<Student> list = pagStudent.getList(); for (Student student : list) { System.out.println(student); } System.out.println(pagStudent.getPagsize()); System.out.println(pagStudent.getList()); response.sendRedirect(request.getContextPath() + "/StudentPaging.jsp"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); request.getSession().setAttribute("msg", "分頁展示資料錯誤"); response.sendRedirect(request.getContextPath() + "/msg.jsp"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
第五步:建立一個Servlet包,裡邊包含兩個方法
package com.qf.service;
import java.sql.SQLException;
import java.util.List;
import com.qf.dao.PagDao;
import com.qf.javabean.PagStudent;
import com.qf.javabean.Student;
public class StudentService {
public com.qf.javabean.PagStudent<Student> findPage(int currentpage, int pagesize) throws SQLException {
PagDao dao= new PagDao();
int totalcount= dao.findcount();//呼叫兩個方法
List<Student> list=dao.findListPage(currentpage,pagesize); //
return new PagStudent<Student>(currentpage,pagesize,totalcount,list);
}
}
第六步:連線資料庫的Dao,裡邊執行SQL語句
package com.qf.dao;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import com.qf.javabean.Student;
import com.qf.utils.DataSourceUtiles;
public class PagDao {
public int findcount() throws SQLException {
// TODO Auto-generated method stub
QueryRunner runner= new QueryRunner();
String sql = "select count(*) from student;";
Connection conn = DataSourceUtiles.getConnection();
Object query = runner.query(conn,sql,new ScalarHandler());
//DataSourceUtiles.close(conn);
System.out.println("資料庫可以走到聚合函式");
return ((Long)query).intValue();//此處的query為long型,轉化
}
public List<Student> findListPage(int currentpage, int pagesize) throws SQLException {
// TODO Auto-generated method stub
QueryRunner runner= new QueryRunner();
String sql="select *from student limit ?,?;";
Connection connection = DataSourceUtiles.getConnection();
List<Student> list = runner.query(connection, sql, new BeanListHandler<Student>(Student.class), (currentpage-1)*pagesize,pagesize);
System.out.println("這一個資料也可以走到的");
for (Student student : list) {
System.out.println(student);
}
//DataSourceUtiles.close(connection);
return list;
}
}