使用Servlet和jsp完成分頁
本次分頁功能的實現使用了servlet+jsp+mysql
一、實現前的準備
1.本次分頁我們使用MVC三層架構
進行實現
如果對mvc框沒有了解,請移步我的另一篇部落格MVC三層架構在Java專案中的應用
2.專案結構如下
3.c3p0連線池:C3P0Util.java、c3p0-config.xml
資料庫連線池工具包-C3P0Util.java
/** * @author Zhao Wen * @date 2020年6月5日上午10:40:42 * @filename C3P0Util.java * @details C3P0連線池工具包 */ public class C3P0Util { private static ComboPooledDataSource dataSource = new ComboPooledDataSource("zhaowen"); public static ComboPooledDataSource getDataSource(){ return dataSource; } public static Connection getConnection(){ try { return (Connection) dataSource.getConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static void release(Connection conn,Statement stmt,ResultSet rs){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } rs=null; } if(stmt!=null){ try { stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } stmt=null; } if(conn!=null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } conn=null; } } public static void release(Connection conn,PreparedStatement ps,ResultSet rs){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } rs=null; } if(ps!=null){ try { ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } ps=null; } if(conn!=null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } conn=null; } } public static void release(Connection conn){ if(conn!=null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } conn=null; } } }
資料庫裡連線池配置檔案-c3p0-config.xml(需要自行修改jdbcUrl
、user
、password
屬性值)
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl"> jdbc:mysql://localhost:3306/student </property> <property name="user">root</property> <property name="password">666666</property> <property name="checkoutTimeout">30000</property> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> </default-config> <!-- 本次連線使用配置 --> <named-config name="zhaowen"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl"> jdbc:mysql://localhost:3306/student </property> <property name="user">root</property> <property name="password">666666</property> <property name="initialPoolSize">5</property> <property name="maxPoolSize">50</property> </named-config> </c3p0-config>
對於資料庫連線池有疑問的可以檢視我另一篇部落格資料庫連線池c3p0、dbcp和dbutils工具類的使用
二、後端實現
分頁JavaBean:PageBean.java
說明:分頁JavaBean,儲存分頁資訊,方便在Web層顯示
private List<T> stuInfoList = new ArrayList<>(); // 每頁顯示資訊List,此處使用泛型可提高程式碼複用率 private int currentPage; // 當前瀏覽頁 private int currentCount; // 當前頁顯示條數 private int totalPage; // 總頁數 private int totalCount; // 資訊總條數
分頁Servlet:PageShowServlet.java
說明:控制器 Servlet層,接收使用者請求,呼叫service層分頁功能實現程式碼獲取資料,跳轉(轉發)頁面
PageShowService stuinfoService = new PageShowService();
PageBean pageBean = null;
String cp = request.getParameter("currentPage");
int currentPage = 1;
if (cp != null) {
Integer cpInt = Integer.valueOf(cp);
if (cpInt != -1) {
currentPage = cpInt; // 當前瀏覽頁數
}
}
int currentCount = 20; // 每頁顯示資訊數
try {
pageBean = stuinfoService.findPageBean(currentPage, currentCount);
} catch (SQLException e) {
e.printStackTrace();
System.out.print("分頁資訊查詢失敗");
}
此處通過前端頁面傳送的引數CurrentPage,來獲知具體請求的頁數;再通過呼叫Service方法中的findPageBean()方法,來獲取分頁資料。
分頁Service:PageShowService.java
說明:給servlet層提供分頁查詢功能方法呼叫,呼叫Dao層資料分頁方法查詢獲取資料
public PageBean findPageBean(int currentPage, int currentCount) throws SQLException {
PageBean<Userinfo> pageBean = new PageBean<>();
StuInfoDao stuInfoDaoImpl = new StuInfoDaoImpl();
pageBean.setCurrentPage(currentPage);
pageBean.setCurrentCount(currentCount);
int totalCount = stuInfoDaoImpl.getTotalCount();
int totalPage = (int) Math.ceil(1.0 * totalCount / currentCount);
pageBean.setTotalPage(totalPage);
pageBean.setTotalCount(stuInfoDaoImpl.getTotalCount());
// 分段獲取使用者資訊
int index = (currentPage - 1) * currentCount;
pageBean.setStuInfoList(stuInfoDaoImpl.findStuListForPageBean(index, currentCount));
return pageBean;
}
-
使用PageBean.java中的getter/setter方法,對分頁屬性進行封裝,其中資訊列表(stuinfoList)和資訊總條數(totalcount),必須要在呼叫Dao實現類查詢;
-
而資訊總頁數,需要根據每頁顯示數(CurrentCount)和資訊總數(stuinfoList)來判斷,所以此處我們使用公式
總頁數(totalPage)=Math.ceil(總條數 /當前顯示的條數)【非四捨五入,應前進】
轉換為Java程式碼就是
int totalPage = Math.ceil(totalCount/currentCount)
-
每次呼叫分頁資料時,為了準確獲取到指定資料,我們需要一個值,來在分段查詢時作為一個初始值。
此處我們使用index來表示,而index的計算公式如下:
index=(當前頁數currentPage-1)*每頁顯示的條數(currentCount)
轉換為Java程式碼就是
int index = (currentPage - 1) * currentCount;
index值會隨著當前瀏覽頁數和每一頁顯示條數限制:
例如,當每頁限制顯示4條時,inde值變化情況如下:
頁數 | 開始索引 | 每頁顯示條數 |
1 | 0 | 4 |
2 | 4 | 4 |
3 | 8 | 4 |
4 | 12 | 4 |
分頁Dao:StuInfoDaoImpl.java
說明:給Service層提供分頁功能方法,直接接觸資料庫(一般使用DBUtils封裝的工具類操作資料庫/一般 作為抽象介面,新建 xxDaoImpl對其進行實現)
獲取指定表的記錄總數:getTotalCount()
public int getTotalCount() throws SQLException {
String sql = "select count(*) from userInfo";
Long count = new QueryRunner(dataSource).query(sql, new ScalarHandler<>());
return count.intValue();
}
獲取分頁資料列表:findStuListForPageBean(int index,int currentCount)
public List<Userinfo> findStuListForPageBean(int index, int currentCount) throws SQLException {
String sql = "select sno,name,age,score from userInfo limit ? , ?";
List<Userinfo_0134> stuInfoList = new QueryRunner(dataSource).query(sql,
new BeanListHandler<>(Userinfo), index, currentCount);
return stuInfoList;
}
此處使用limit關鍵字,通過每次呼叫引數index和currentCount的值,來獲取指定區段的資料。
三、前端介面
分頁顯示頁面:page_list.jsp
說明:使用JSTL的c:forEach標籤遍歷分頁資料,在前臺進行展示
顯示頁面
<!-- 資訊展示 -->
<table border="1">
<tr>
<td>學號</td>
<td>姓名</td>
<td>年齡</td>
<td>成績</td>
</tr>
<c:forEach items="${pageBean.stuInfoList}" var="stuinfo">
<tr>
<td>${stuinfo.sno}</td>
<td>${stuinfo.name}</td>
<td>${stuinfo.age}</td>
<td>${stuinfo.score}</td>
</tr>
</c:forEach>
</table>
<p>----------------------------------------------------------------------------</p>
顯示分頁資料:當前瀏覽頁、總頁數、總資訊條數
<div>
<span>當前頁:${pageBean.currentPage}/${pageBean.totalPage}</span>
|
<span>總頁數:${pageBean.totalPage}</span>
|
<span>總資訊數:${pageBean.totalCount}</span>
</div>
顯示分頁頁碼:頁碼、前一頁、後一頁實現
<div>
<!--首頁-->
<span><a href="${pageContext.request.contextPath}/PageShowServlet_0134? currentPage=1">首頁</a>
</span>
||
<!--前一頁-->
<span><a href="${pageContext.request.contextPath}/PageShowServlet?currentPage=${pageBean.currentPage - 1}">上一頁</a>
</span>
<!--頁碼-->
<c:forEach begin="1" end="${pageBean.totalCount/20+1}" var="pageCount">
|
<a href="${pageContext.request.contextPath}/PageShowServlet?currentPage=${pageCount}">${pageCount}</a>
|
</c:forEach>
|
<!--後一頁-->
<span><a href="${pageContext.request.contextPath}/PageShowServlet?currentPage=${pageBean.currentPage + 1}">下一頁</a>
</span>
|
<!--尾頁-->
<span><a
<fmt:formatNumber var="lastPage" value="${pageBean.totalCount/20+1}" pattern="#" />
href="${pageContext.request.contextPath}/PageShowServlet?currentPage=${lastPage - 1}">尾頁</a>
</span>
</div>
四、總結
要使用Servlet完成分頁,我們首先要定義JavaBean用於資料封裝、然後依次編寫Dao資料庫DDL語句、分頁Servlet用於與前端互動,最後再編寫前端頁面並使用EL表示式接收資料並顯示。
本文來自部落格園,作者:趙雯,轉載請註明原文連結:https://www.cnblogs.com/ybqdren/p/15476327.html