Java Web实现分页查询
目錄
- 使用工具:
- 使用Jar包:
- 項目下載連接:
- 數據庫表
- 實體類:
- 用戶實體類:
- 分頁實例化:
- 在Dao接口中定義2個方法:
- 接口:
- 實現Dao接口方法解析:
- service層:
- 接口:
- 接口實現:
- 工具類:
- Servlet:
- web.xml:
- c3p0-config.xml
- 信息展示頁面:
- 效果展示:
使用工具:
JavaJDK1.8
Tomcat 8.5.33
IDEA
MySQL5.6
使用Jar包:
- c3p0-0.9.1.2.jar
- commons-dbutils-1.4.jar
- javax.annotation.jar
- javax.ejb.jar
- javax.jms.jar
- javax.persistence.jar
- javax.resource.jar
- javax.servlet.jar
- javax.servlet.jsp.jar
- javax.transaction.jar
- jstl-1.2.jar
- mysql-connector-java-8.0.13.jar
- junit-4.12.jar + hamcrest-core-1.3.jar 這個兩個缺一不可 (junit-4.8.jar以上可以代替這兩個jar包)
項目下載連接:
微云鏈接:https://share.weiyun.com/WA6AmSix
數據庫表
CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(255) DEFAULT NULL,`age` int(11) DEFAULT NULL,PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8;實體類:
用戶實體類:
public class User {private Integer id;private String name;private Integer age;public User() {}public User(Integer id, String name, Integer age) {this.id = id;this.name = name;this.age = age;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +", age=" + age +'}';} }分頁實例化:
定義5個屬性:
Integer pageNum :用來記錄當前頁面的頁碼
Integer pageSize :可以自定義當前頁面最大顯示多少條數據
Long totalSize :記錄數據庫存儲的數據總共多少條
Integer pageCount : 將數據庫的 總數據量 除以 當前頁面最大顯示數據量 得到 數據可以分多少頁
List<T> data:存放每一頁要顯示的數據
當總數據量 除以 當前頁面顯示的數據量 剛好等于 0時數據頁面不再 + 1,
當總數據量 除以 當前頁面顯示的數據量 有余數時,數據頁面 + 1(額外加一頁顯示剩余的數據)。
例如:有21條數據,每頁顯示10條數據,需要3頁才能把全部的數據展示出來。
如果剛好20條數據,每頁顯示10條數據,2頁剛好展示全部的數據。
在Dao接口中定義2個方法:
接口:
findByPage方法:當前頁面的頁碼 和 頁面能顯示的最大數據量 作為參數返回通過mysql處理 顯示當前頁面對應的數據。
getCount方法:統計數據庫數據的總量。
實現Dao接口方法解析:
例如:
目前數據庫數據:
調用findByPage方法:
例如:
pageNum = 0; 從第幾頁開始顯示
pageSize = 10; 顯示10條數據
參數:(pageNum-1) * pageSize
剛進入看到的頁面為第一頁,數據庫LIMIT 是下標第0頁開始查詢,所以減去1。
getCount方法:
統計數據庫數據的總量。
例如:
service層:
接口:
PageBean findByPage(Integer pageNum, Integer pageSize)方法:
將pageNum; pageSize; totalSize; pageCount; data; 這些參數通過 PageBean 返回給jsp頁面。
接口實現:
public class UserServiceImpl implements UserService {@Overridepublic PageBean<User> findByPage(Integer pageNum, Integer pageSize) {UserDao studentDao = new UserDaoImpl();List<User> data = studentDao.findByPage(pageNum, pageSize); // 根據條件獲取數據庫對應數據long totalSize = 0;totalSize = studentDao.getCount(); // 獲取數據庫可分多少頁數據PageBean<User> pageBean = new PageBean<>(pageNum, pageSize, totalSize, data); // 將以上2條方法封裝在一起,返回給Servlet;if (pageNum > pageBean.getPageCount()){pageBean.setPageNum(pageBean.getPageCount());}return pageBean;}工具類:
import com.mchange.v2.c3p0.ComboPooledDataSource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;public class JDBCUtil {static ComboPooledDataSource dataSource = null;static{dataSource = new ComboPooledDataSource();}public static DataSource getDataSouce() {return dataSource;}/*** 獲取連接對象* @return* @throws SQLException*/public static Connection getConn() throws SQLException{return dataSource.getConnection();}/*** 釋放資源* @param conn* @param st* @param rs*/public static void release(Connection conn , Statement st , ResultSet rs){closeRs(rs);closeSt(st);closeConn(conn);}public static void release(Connection conn , Statement st){closeSt(st);closeConn(conn);}private static void closeRs(ResultSet rs){try {if(rs != null){rs.close();}} catch (SQLException e) {e.printStackTrace();}finally{rs = null;}}private static void closeSt(Statement st){try {if(st != null){st.close();}} catch (SQLException e) {e.printStackTrace();}finally{st = null;}}private static void closeConn(Connection conn){try {if(conn != null){conn.close();}} catch (SQLException e) {e.printStackTrace();}finally{conn = null;}} }Servlet:
import io.vvcat.been.PageBean; import io.vvcat.been.User; import io.vvcat.service.UserService; import io.vvcat.service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;/*** @Author ??VVcat??* @Date 2020/6/19 18:02 星期五* @ProjectName PageSelect* @PackageName io.vvcat.Servlet* @ClassName ServletListUser* @Email: 206647497@qq.com* @Blog: vvcat.io* @CSDN: https://blog.csdn.net/qq_44989881* @Version 1.0**/ public class ServletListUser extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String pageNum = request.getParameter("pageNum"); // 獲取前端頁面傳過來的頁碼String pageSize = request.getParameter("pageSize"); // 獲取前端頁面顯示的數據int pageN = 0;int pageS = 0;if (pageNum==null||pageNum.trim().length()==0){ // 當第一次打開頁面時是沒有頁碼的,數據為null需要為頁碼賦值pageN = 1;}else {pageN=Integer.parseInt(pageNum); if (pageN<1){ // 如果請求的頁面小于 1 那么就將 pageN 賦值為 1 ,限制上一頁請求傳遞過來的值是一個負數pageN=1;}}if (pageSize==null||pageSize.trim().length()==0){ // 為頁面顯示的數據進行初始化pageS=10; // 如果此處修改為 8,那么每頁最多只會顯示 8 條數據,設置為 5 ,那么每頁最多只會顯示 5 條數據}else {pageS=Integer.parseInt(pageSize); }UserService userService = new UserServiceImpl(); // 調用UserService 服務 PageBean<User> pageBean = userService.findByPage(pageN, pageS); // 獲取頁面獲取的值傳遞到數據庫,獲取對應的數據。request.setAttribute("pageBean", pageBean);request.getRequestDispatcher("/user.jsp").forward(request, response); // 處理完成后返回user.jsp頁面進行數據渲染。}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);} }web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"><display-name>user</display-name><welcome-file-list><welcome-file>index.html</welcome-file><!--<welcome-file>index.htm</welcome-file>--><welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file><!--<welcome-file>default.htm</welcome-file>--><welcome-file>default.jsp</welcome-file></welcome-file-list><servlet><description></description><display-name>ServletListUser</display-name><servlet-name>ServletListUser</servlet-name><servlet-class>io.vvcat.Servlet.ServletListUser</servlet-class></servlet><servlet-mapping><servlet-name>ServletListUser</servlet-name><url-pattern>/ServletListUser</url-pattern></servlet-mapping></web-app>c3p0-config.xml
要對以下三條進行修改和確認
<property name="jdbcUrl">jdbc:mysql://localhost/studnets?serverTimezone=GMT%2B8</property> <property name="user">root</property> <property name="password">123456</property>- 設置 數據庫連接地址 jdbcUrl
- 設置 數據庫的用戶名 user
- 設置 數據庫密碼 password
注: serverTimezone=GMT%2B8 防止在使用IDEA對高版本數據庫連接時出現時區報錯問題。
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config><!-- default-config 默認的配置, --><default-config><property name="driverClass">com.mysql.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql://localhost/db?serverTimezone=GMT%2B8</property><property name="user">root</property><property name="password">123456</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><!-- This app is massive! --><named-config name="oracle"> <property name="acquireIncrement">50</property><property name="initialPoolSize">100</property><property name="minPoolSize">50</property><property name="maxPoolSize">1000</property><!-- intergalactoApp adopts a different approach to configuring statement caching --><property name="maxStatements">0</property> <property name="maxStatementsPerConnection">5</property><!-- he's important, but there's only one of him --><user-overrides user="master-of-the-universe"> <property name="acquireIncrement">1</property><property name="initialPoolSize">1</property><property name="minPoolSize">1</property><property name="maxPoolSize">5</property><property name="maxStatementsPerConnection">50</property></user-overrides></named-config></c3p0-config>信息展示頁面:
首頁:第一頁對應頁碼設置為1,每次點擊首頁,將1傳遞到后臺,進行查詢數據。
上一頁:點擊上一頁,會獲取當前頁碼 - 1,傳遞到后臺獲取,上一頁的數據。
下一頁:點擊下一頁,會獲取當前頁碼 + 1,傳遞到后臺獲取,下一頁的數據。
尾頁:將總共可分的頁數(即最后一頁),傳遞到后臺,顯示最后一頁的數據。
效果展示:
總結
以上是生活随笔為你收集整理的Java Web实现分页查询的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 使用servlet做学生管理系
- 下一篇: C语言 浮点数从0递增至1.0的过程