您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關分頁查詢功能如何在JavaWeb項目中實現,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
一、MySql實現分頁查詢的SQL語句
1、分頁需求:
客戶端通過傳遞pageNo(頁碼),counter(每頁顯示的條數)兩個參數去分頁查詢數據庫表中的數據,那我們知道MySql數據庫提供了分頁的函數limit m,n,但是該函數的用法和我們的需求不一樣,所以就需要我們根據實際情況去改寫適合我們自己的分頁語句,具體的分析如下:
比如:
查詢第1條到第10條的數據的sql是:select * from table limit 0,10; ->對應我們的需求就是查詢第一頁的數據:select * from table limit (1-1)*10,10;
查詢第10條到第20條的數據的sql是:select * from table limit 10,20; ->對應我們的需求就是查詢第二頁的數據:select * from table limit (2-1)*10,10;
查詢第20條到第30條的數據的sql是:select * from table limit 20,30; ->對應我們的需求就是查詢第三頁的數據:select * from table limit (3-1)*10,10;
2、總結
通過上面的分析,可以得出符合我們自己需求的分頁sql格式是:select * from table limit (pageNo-1)*counter,counter; 其中pageNo是頁碼,counter是每頁顯示的條數。
二、JavaWeb程序
1、創建PageBeanUtils.java工具類
package com.ambow.utils; import java.util.List; public class PageBeanUtils<T> { private int prePage;//上一頁 private int nextPage;//下一頁 private int firstPage=1;//首頁 private int lastPage;//尾頁 private int currentPage = 1;//當前 private int totalPage;//總頁數 private int pageSize;//每頁顯示條數,默認顯示10條 private int totalData;//數據總條數 private List<T> pageData;//數據 public PageBeanUtils(int currentPage,int pageSize, int totalData) { this.currentPage = currentPage; this.pageSize = pageSize; this.totalData = totalData; //計算獲得總頁數(尾頁) // this.totalPage = this.lastPage = (totalData+pageSize-1)/pageSize; this.totalPage = this.lastPage = (int)Math.ceil((double)totalData/pageSize); //防止當前頁小于1 this.currentPage = Math.max(this.currentPage, 1); //防止當前頁大于總的頁數 this.currentPage = Math.min(this.totalPage, this.currentPage); //設置上一頁,上一頁不能小于1 this.prePage = Math.max(this.currentPage-1, 1); //設置下一頁,下一頁不能大于總頁數 this.nextPage = Math.min(this.currentPage+1, this.totalPage); /** * ceil public static double ceil(double a) 返回最小的(最接近負無窮大) double 值,該值大于等于參數,并等于某個整數。特殊情況如下: 如果參數值已經等于某個整數,那么結果與該參數相同。 如果參數為 NaN、無窮大、正 0 或負 0,那么結果與參數相同。 如果參數值小于 0,但是大于 -1.0,那么結果為負 0。 注意, Math.ceil(x) 的值與 -Math.floor(-x) 的值完全相同。 參數: a - 一個值。 返回: 最小(最接近負無窮大)浮點值,該值大于等于該參數,并等于某個整數。 */ } public PageBeanUtils(int prePage, int nextPage, int firstPage, int lastPage, int currentPage, int totalPage, int pageSize, int totalData, List<T> pageData) { super(); this.prePage = prePage; this.nextPage = nextPage; this.firstPage = firstPage; this.lastPage = lastPage; this.currentPage = currentPage; this.totalPage = totalPage; this.pageSize = pageSize; this.totalData = totalData; this.pageData = pageData; } public int getPrePage() { return prePage; } public void setPrePage(int prePage) { this.prePage = prePage; } public int getNextPage() { return nextPage; } public void setNextPage(int nextPage) { this.nextPage = nextPage; } public int getFirstPage() { return firstPage; } public void setFirstPage(int firstPage) { this.firstPage = firstPage; } public int getLastPage() { return lastPage; } public void setLastPage(int lastPage) { this.lastPage = lastPage; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalData() { return totalData; } public void setTotalData(int totalData) { this.totalData = totalData; } public List<T> getPageData() { return pageData; } public void setPageData(List<T> pageData) { this.pageData = pageData; } /* * * * totalPage = (totalData+pageSize-1)/pageSize; * * * */ }
2、在接口里面定義分頁查詢的方法
package com.ambow.dao; import java.util.List; import com.ambow.pojo.Good; public interface IGoodDao { //增刪改查 public void add(Good good); public void delete(Good good); public void update(Good good); public void query(Good good); public Good queryOne(Good good); public List<Good> queryMore(Good good); public List<Good> queryByName(String name);//根據商家名稱進行模糊查詢 //條件分頁查詢 public List<Good> queryByName(String name,int currentPage,int pageSize); //獲取滿足某個條件的總記錄數 public int getTotalNum(String name); }
3、在接口的實現類里面實現方法
package com.ambow.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.ambow.dao.IGoodDao; import com.ambow.pojo.Good; import com.ambow.utils.DBUtils; public class GoodDaoImpl implements IGoodDao { DBUtils db = new DBUtils(); @Override public void add(Good good) { Connection conn = null; PreparedStatement pstmt = null; String sql = "insert into good (name,address,tel,dishes) values (?,?,?,?)"; try { conn = DBUtils.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, good.getName()); pstmt.setString(2, good.getAddress()); pstmt.setString(3, good.getTel()); pstmt.setString(4, good.getDishes()); int isOk = pstmt.executeUpdate(); //System.out.println("add-----"+isOk); } catch (SQLException e) { e.printStackTrace(); } } @Override public void delete(Good good) { Connection conn = null; PreparedStatement pstmt = null; String sql = "delete from good where id = ?"; try { conn = DBUtils.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setInt(1, good.getId()); int isOk = pstmt.executeUpdate(); System.out.println("delete-----"+isOk); } catch (SQLException e) { e.printStackTrace(); } } @Override public void update(Good good) { Connection conn = null; PreparedStatement pstmt = null; String sql = "update good set name=?,address=?,tel=?,dishes=? where id=?"; try { conn = DBUtils.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, good.getName()); pstmt.setString(2, good.getAddress()); pstmt.setString(3, good.getTel()); pstmt.setString(4, good.getDishes()); pstmt.setInt(5,good.getId()); int isOk = pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } @Override public void query(Good good) { // TODO Auto-generated method stub } @Override public Good queryOne(Good good) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "select * from good where id = ?"; Good gd = null; try { conn = DBUtils.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setInt(1, good.getId()); rs = pstmt.executeQuery(); while(rs.next()){ gd = new Good(rs.getInt(1),rs.getString(2),rs.getString(3), rs.getString(4),rs.getString(5)); } } catch (SQLException e) { e.printStackTrace(); } return gd; } @Override public List<Good> queryMore(Good good) { // TODO Auto-generated method stub return null; } @Override public List<Good> queryByName(String name) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "select * from good where name like ?"; List<Good> goodList = new ArrayList<Good>(); try { conn = DBUtils.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, "%"+name+"%"); rs = pstmt.executeQuery(); while(rs.next()){ goodList.add(new Good(rs.getInt(1),rs.getString(2),rs.getString(3), rs.getString(4),rs.getString(5))); } } catch (SQLException e) { e.printStackTrace(); } return goodList; } @Override public List<Good> queryByName(String name, int currentPage, int pageSize) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "select * from good where name like ? limit ?,?"; List<Good> goodList = new ArrayList<Good>(); try { conn = DBUtils.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, "%"+name+"%"); pstmt.setInt(2,(currentPage-1)*pageSize); pstmt.setInt(3,pageSize); rs = pstmt.executeQuery(); while(rs.next()){ goodList.add(new Good(rs.getInt(1),rs.getString(2),rs.getString(3), rs.getString(4),rs.getString(5))); } } catch (SQLException e) { e.printStackTrace(); } return goodList; } @Override public int getTotalNum(String name) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "select count(id) from good where name like ?"; int total = 0; try { conn = DBUtils.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, "%"+name+"%"); rs = pstmt.executeQuery(); while(rs.next()){ total = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } return total; } }
4.在Servlet里面調用實現類里面的分頁查詢方法
package com.ambow.servlet; import java.io.IOException; import java.util.List; 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 com.ambow.dao.IGoodDao; import com.ambow.dao.impl.GoodDaoImpl; import com.ambow.pojo.Good; import com.ambow.utils.PageBeanUtils; @WebServlet("/QueryServlet") public class QueryServlet extends HttpServlet { private static final long serialVersionUID = 1L; private IGoodDao goodDao = new GoodDaoImpl(); public QueryServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String keywords = request.getParameter("kw"); String method = request.getParameter("method"); if("add".equals(method)){ String name = request.getParameter("name"); String address = request.getParameter("address"); String tel = request.getParameter("tel"); String dishes = request.getParameter("dishes"); Good good = new Good(0,name,address,tel,dishes); goodDao.add(good); //調用dao的查詢方法,返回一個List List<Good> goods = goodDao.queryByName(keywords); request.setAttribute("list", goods); request.getRequestDispatcher("goods.jsp").forward(request, response); }else if("search".equals(method)){ if(null==keywords) { keywords=""; } int currentPage = 1; try { currentPage=Integer.parseInt(request.getParameter("curPage")); if(currentPage<=0) { currentPage = 1; } }catch(Exception e) { currentPage = 1; } int pageSize=10; int totalData = goodDao.getTotalNum(keywords); int totalPage = (int)Math.ceil((double)totalData/pageSize); if(currentPage>totalPage){ currentPage = totalPage; } List<Good> goods = goodDao.queryByName(keywords,currentPage,pageSize); PageBeanUtils pg = new PageBeanUtils(currentPage,pageSize,totalData); pg.setPageData(goods); request.setAttribute("pg", pg); request.getRequestDispatcher("good2.jsp").forward(request, response); }else if("delete".equals(method)){ System.out.println(keywords); //實現刪除 String id = request.getParameter("id"); Good good = new Good(); good.setId(Integer.valueOf(id)); goodDao.delete(good); //調用dao的查詢方法,返回一個List List<Good> goods = goodDao.queryByName(keywords); request.setAttribute("list", goods); request.getRequestDispatcher("goods.jsp").forward(request, response); }else if("queryById".equals(method)){ //查詢一個 String id = request.getParameter("id"); Good good = new Good(); good.setId(Integer.valueOf(id)); good = goodDao.queryOne(good); //調用dao的查詢方法,返回一個good request.setAttribute("good", good); request.getRequestDispatcher("update.jsp").forward(request, response); }else if("update".equals(method)){ String id = request.getParameter("id"); String name = request.getParameter("name"); String address = request.getParameter("address"); String tel = request.getParameter("tel"); String dishes = request.getParameter("dishes"); Good good = new Good(Integer.valueOf(id),name,address,tel,dishes); goodDao.update(good); //調用dao的查詢方法,返回一個List List<Good> goods = goodDao.queryByName(keywords); request.setAttribute("list", goods); request.getRequestDispatcher("goods.jsp").forward(request, response); }else{ //調用dao的查詢方法,返回一個List List<Good> goods = goodDao.queryByName(keywords); request.setAttribute("list", goods); request.getRequestDispatcher("goods.jsp").forward(request, response); } } }
5.在JSP頁面獲取Servlet里面傳過來的數據
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" import="java.util.ArrayList,com.ambow.pojo.Good, com.ambow.pojo.User,com.ambow.utils.PageBeanUtils"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>外賣系統的搜索功能</title> </head> <body> <form action="QueryServlet?method=search" method="POST"> <input type="text" name="kw"/><input type="submit" value="搜索"/><a href=" ">添加商家</a > <table border="1"> <tr><th>商家店名</th><th>商家地址</th><th>商家電話</th><th>經營菜品</th><th colspan="2">編輯</th></tr> <c:forEach items="${pg.pageData}" var="g"> <tr><td>${g.name}</td><td>${g.address}</td><td>${g.tel}</td><td>${g.dishes}</td> <td><a href="QueryServlet?method=queryById&id=${g.id}">修改</a ></td> <td><a href="QueryServlet?method=delete&id=${g.id}" onClick="return confirm('確認刪除本條數據嗎?');">刪除</a ></td></tr> </c:forEach> </table> <a href="QueryServlet?method=search&curPage=${pg.firstPage}">首頁</a > <a href="QueryServlet?method=search&curPage=${pg.currentPage - 1}">上一頁</a > <a href="QueryServlet?method=search&curPage=${pg.currentPage + 1}">下一頁</a > <a href="QueryServlet?method=search&curPage=${pg.lastPage}">尾頁</a > 當前第${pg.currentPage}頁/共${pg.totalPage}頁 每頁顯示${pg.pageSize}條 </form> </body> </html>
以上就是分頁查詢功能如何在JavaWeb項目中實現,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。