小言_互联网的博客

JavaWeb入门之简单分页查询功能实现

379人阅读  评论(0)

一、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工具类


  
  1. package com.ambow.utils;
  2. import java.util.List;
  3. public class PageBeanUtils<T> {
  4. private int prePage; //上一页
  5. private int nextPage; //下一页
  6. private int firstPage= 1; //首页
  7. private int lastPage; //尾页
  8. private int currentPage = 1; //当前
  9. private int totalPage; //总页数
  10. private int pageSize; //每页显示条数,默认显示10条
  11. private int totalData; //数据总条数
  12. private List<T> pageData; //数据
  13. public PageBeanUtils(int currentPage,int pageSize, int totalData) {
  14. this.currentPage = currentPage;
  15. this.pageSize = pageSize;
  16. this.totalData = totalData;
  17. //计算获得总页数(尾页)
  18. // this.totalPage = this.lastPage = (totalData+pageSize-1)/pageSize;
  19. this.totalPage = this.lastPage = ( int)Math.ceil(( double)totalData/pageSize);
  20. //防止当前页小于1
  21. this.currentPage = Math.max( this.currentPage, 1);
  22. //防止当前页大于总的页数
  23. this.currentPage = Math.min( this.totalPage, this.currentPage);
  24. //设置上一页,上一页不能小于1
  25. this.prePage = Math.max( this.currentPage- 1, 1);
  26. //设置下一页,下一页不能大于总页数
  27. this.nextPage = Math.min( this.currentPage+ 1, this.totalPage);
  28. /**
  29. * ceil
  30. public static double ceil(double a)
  31. 返回最小的(最接近负无穷大) double 值,该值大于等于参数,并等于某个整数。特殊情况如下:
  32. 如果参数值已经等于某个整数,那么结果与该参数相同。
  33. 如果参数为 NaN、无穷大、正 0 或负 0,那么结果与参数相同。
  34. 如果参数值小于 0,但是大于 -1.0,那么结果为负 0。
  35. 注意, Math.ceil(x) 的值与 -Math.floor(-x) 的值完全相同。
  36. 参数:
  37. a - 一个值。
  38. 返回:
  39. 最小(最接近负无穷大)浮点值,该值大于等于该参数,并等于某个整数。
  40. */
  41. }
  42. public PageBeanUtils(int prePage, int nextPage, int firstPage, int lastPage, int currentPage, int totalPage,
  43. int pageSize, int totalData, List<T> pageData) {
  44. super();
  45. this.prePage = prePage;
  46. this.nextPage = nextPage;
  47. this.firstPage = firstPage;
  48. this.lastPage = lastPage;
  49. this.currentPage = currentPage;
  50. this.totalPage = totalPage;
  51. this.pageSize = pageSize;
  52. this.totalData = totalData;
  53. this.pageData = pageData;
  54. }
  55. public int getPrePage() {
  56. return prePage;
  57. }
  58. public void setPrePage(int prePage) {
  59. this.prePage = prePage;
  60. }
  61. public int getNextPage() {
  62. return nextPage;
  63. }
  64. public void setNextPage(int nextPage) {
  65. this.nextPage = nextPage;
  66. }
  67. public int getFirstPage() {
  68. return firstPage;
  69. }
  70. public void setFirstPage(int firstPage) {
  71. this.firstPage = firstPage;
  72. }
  73. public int getLastPage() {
  74. return lastPage;
  75. }
  76. public void setLastPage(int lastPage) {
  77. this.lastPage = lastPage;
  78. }
  79. public int getCurrentPage() {
  80. return currentPage;
  81. }
  82. public void setCurrentPage(int currentPage) {
  83. this.currentPage = currentPage;
  84. }
  85. public int getTotalPage() {
  86. return totalPage;
  87. }
  88. public void setTotalPage(int totalPage) {
  89. this.totalPage = totalPage;
  90. }
  91. public int getPageSize() {
  92. return pageSize;
  93. }
  94. public void setPageSize(int pageSize) {
  95. this.pageSize = pageSize;
  96. }
  97. public int getTotalData() {
  98. return totalData;
  99. }
  100. public void setTotalData(int totalData) {
  101. this.totalData = totalData;
  102. }
  103. public List<T> getPageData() {
  104. return pageData;
  105. }
  106. public void setPageData(List<T> pageData) {
  107. this.pageData = pageData;
  108. }
  109. /*
  110. *
  111. *
  112. * totalPage = (totalData+pageSize-1)/pageSize;
  113. *
  114. *
  115. * */
  116. }

2、在接口里面定义分页查询的方法


  
  1. package com.ambow.dao;
  2. import java.util.List;
  3. import com.ambow.pojo.Good;
  4. public interface IGoodDao {
  5. //增删改查
  6. public void add(Good good);
  7. public void delete(Good good);
  8. public void update(Good good);
  9. public void query(Good good);
  10. public Good queryOne(Good good);
  11. public List<Good> queryMore(Good good);
  12. public List<Good> queryByName(String name); //根据商家名称进行模糊查询
  13. //条件分页查询
  14. public List<Good> queryByName(String name,int currentPage,int pageSize);
  15. //获取满足某个条件的总记录数
  16. public int getTotalNum(String name);
  17. }

3、在接口的实现类里面实现方法


  
  1. package com.ambow.dao.impl;
  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import com.ambow.dao.IGoodDao;
  9. import com.ambow.pojo.Good;
  10. import com.ambow.utils.DBUtils;
  11. public class GoodDaoImpl implements IGoodDao {
  12. DBUtils db = new DBUtils();
  13. @Override
  14. public void add(Good good) {
  15. Connection conn = null;
  16. PreparedStatement pstmt = null;
  17. String sql = "insert into good (name,address,tel,dishes) values (?,?,?,?)";
  18. try {
  19. conn = DBUtils.getConnection();
  20. pstmt = conn.prepareStatement(sql);
  21. pstmt.setString( 1, good.getName());
  22. pstmt.setString( 2, good.getAddress());
  23. pstmt.setString( 3, good.getTel());
  24. pstmt.setString( 4, good.getDishes());
  25. int isOk = pstmt.executeUpdate();
  26. //System.out.println("add-----"+isOk);
  27. } catch (SQLException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. @Override
  32. public void delete(Good good) {
  33. Connection conn = null;
  34. PreparedStatement pstmt = null;
  35. String sql = "delete from good where id = ?";
  36. try {
  37. conn = DBUtils.getConnection();
  38. pstmt = conn.prepareStatement(sql);
  39. pstmt.setInt( 1, good.getId());
  40. int isOk = pstmt.executeUpdate();
  41. System.out.println( "delete-----"+isOk);
  42. } catch (SQLException e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. @Override
  47. public void update(Good good) {
  48. Connection conn = null;
  49. PreparedStatement pstmt = null;
  50. String sql = "update good set name=?,address=?,tel=?,dishes=? where id=?";
  51. try {
  52. conn = DBUtils.getConnection();
  53. pstmt = conn.prepareStatement(sql);
  54. pstmt.setString( 1, good.getName());
  55. pstmt.setString( 2, good.getAddress());
  56. pstmt.setString( 3, good.getTel());
  57. pstmt.setString( 4, good.getDishes());
  58. pstmt.setInt( 5,good.getId());
  59. int isOk = pstmt.executeUpdate();
  60. } catch (SQLException e) {
  61. e.printStackTrace();
  62. }
  63. }
  64. @Override
  65. public void query(Good good) {
  66. // TODO Auto-generated method stub
  67. }
  68. @Override
  69. public Good queryOne(Good good) {
  70. Connection conn = null;
  71. PreparedStatement pstmt = null;
  72. ResultSet rs = null;
  73. String sql = "select * from good where id = ?";
  74. Good gd = null;
  75. try {
  76. conn = DBUtils.getConnection();
  77. pstmt = conn.prepareStatement(sql);
  78. pstmt.setInt( 1, good.getId());
  79. rs = pstmt.executeQuery();
  80. while(rs.next()){
  81. gd = new Good(rs.getInt( 1),rs.getString( 2),rs.getString( 3),
  82. rs.getString( 4),rs.getString( 5));
  83. }
  84. } catch (SQLException e) {
  85. e.printStackTrace();
  86. }
  87. return gd;
  88. }
  89. @Override
  90. public List<Good> queryMore(Good good) {
  91. // TODO Auto-generated method stub
  92. return null;
  93. }
  94. @Override
  95. public List<Good> queryByName(String name) {
  96. Connection conn = null;
  97. PreparedStatement pstmt = null;
  98. ResultSet rs = null;
  99. String sql = "select * from good where name like ?";
  100. List<Good> goodList = new ArrayList<Good>();
  101. try {
  102. conn = DBUtils.getConnection();
  103. pstmt = conn.prepareStatement(sql);
  104. pstmt.setString( 1, "%"+name+ "%");
  105. rs = pstmt.executeQuery();
  106. while(rs.next()){
  107. goodList.add( new Good(rs.getInt( 1),rs.getString( 2),rs.getString( 3),
  108. rs.getString( 4),rs.getString( 5)));
  109. }
  110. } catch (SQLException e) {
  111. e.printStackTrace();
  112. }
  113. return goodList;
  114. }
  115. @Override
  116. public List<Good> queryByName(String name, int currentPage, int pageSize) {
  117. Connection conn = null;
  118. PreparedStatement pstmt = null;
  119. ResultSet rs = null;
  120. String sql = "select * from good where name like ? limit ?,?";
  121. List<Good> goodList = new ArrayList<Good>();
  122. try {
  123. conn = DBUtils.getConnection();
  124. pstmt = conn.prepareStatement(sql);
  125. pstmt.setString( 1, "%"+name+ "%");
  126. pstmt.setInt( 2,(currentPage- 1)*pageSize);
  127. pstmt.setInt( 3,pageSize);
  128. rs = pstmt.executeQuery();
  129. while(rs.next()){
  130. goodList.add( new Good(rs.getInt( 1),rs.getString( 2),rs.getString( 3),
  131. rs.getString( 4),rs.getString( 5)));
  132. }
  133. } catch (SQLException e) {
  134. e.printStackTrace();
  135. }
  136. return goodList;
  137. }
  138. @Override
  139. public int getTotalNum(String name) {
  140. Connection conn = null;
  141. PreparedStatement pstmt = null;
  142. ResultSet rs = null;
  143. String sql = "select count(id) from good where name like ?";
  144. int total = 0;
  145. try {
  146. conn = DBUtils.getConnection();
  147. pstmt = conn.prepareStatement(sql);
  148. pstmt.setString( 1, "%"+name+ "%");
  149. rs = pstmt.executeQuery();
  150. while(rs.next()){
  151. total = rs.getInt( 1);
  152. }
  153. } catch (SQLException e) {
  154. e.printStackTrace();
  155. }
  156. return total;
  157. }
  158. }

4.在Servlet里面调用实现类里面的分页查询方法


  
  1. package com.ambow.servlet;
  2. import java.io.IOException;
  3. import java.util.List;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.annotation.WebServlet;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. import com.ambow.dao.IGoodDao;
  10. import com.ambow.dao.impl.GoodDaoImpl;
  11. import com.ambow.pojo.Good;
  12. import com.ambow.utils.PageBeanUtils;
  13. @WebServlet("/QueryServlet")
  14. public class QueryServlet extends HttpServlet {
  15. private static final long serialVersionUID = 1L;
  16. private IGoodDao goodDao = new GoodDaoImpl();
  17. public QueryServlet() {
  18. super();
  19. }
  20. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  21. doPost(request,response);
  22. }
  23. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  24. request.setCharacterEncoding( "utf-8");
  25. response.setCharacterEncoding( "utf-8");
  26. String keywords = request.getParameter( "kw");
  27. String method = request.getParameter( "method");
  28. if( "add".equals(method)){
  29. String name = request.getParameter( "name");
  30. String address = request.getParameter( "address");
  31. String tel = request.getParameter( "tel");
  32. String dishes = request.getParameter( "dishes");
  33. Good good = new Good( 0,name,address,tel,dishes);
  34. goodDao.add(good);
  35. //调用dao的查询方法,返回一个List
  36. List<Good> goods = goodDao.queryByName(keywords);
  37. request.setAttribute( "list", goods);
  38. request.getRequestDispatcher( "goods.jsp").forward(request, response);
  39. } else if( "search".equals(method)){
  40. if( null==keywords) {
  41. keywords= "";
  42. }
  43. int currentPage = 1;
  44. try {
  45. currentPage=Integer.parseInt(request.getParameter( "curPage"));
  46. if(currentPage<= 0) {
  47. currentPage = 1;
  48. }
  49. } catch(Exception e) {
  50. currentPage = 1;
  51. }
  52. int pageSize= 10;
  53. int totalData = goodDao.getTotalNum(keywords);
  54. int totalPage = ( int)Math.ceil(( double)totalData/pageSize);
  55. if(currentPage>totalPage){
  56. currentPage = totalPage;
  57. }
  58. List<Good> goods = goodDao.queryByName(keywords,currentPage,pageSize);
  59. PageBeanUtils pg = new PageBeanUtils(currentPage,pageSize,totalData);
  60. pg.setPageData(goods);
  61. request.setAttribute( "pg", pg);
  62. request.getRequestDispatcher( "good2.jsp").forward(request, response);
  63. } else if( "delete".equals(method)){
  64. System.out.println(keywords);
  65. //实现删除
  66. String id = request.getParameter( "id");
  67. Good good = new Good();
  68. good.setId(Integer.valueOf(id));
  69. goodDao.delete(good);
  70. //调用dao的查询方法,返回一个List
  71. List<Good> goods = goodDao.queryByName(keywords);
  72. request.setAttribute( "list", goods);
  73. request.getRequestDispatcher( "goods.jsp").forward(request, response);
  74. } else if( "queryById".equals(method)){
  75. //查询一个
  76. String id = request.getParameter( "id");
  77. Good good = new Good();
  78. good.setId(Integer.valueOf(id));
  79. good = goodDao.queryOne(good);
  80. //调用dao的查询方法,返回一个good
  81. request.setAttribute( "good", good);
  82. request.getRequestDispatcher( "update.jsp").forward(request, response);
  83. } else if( "update".equals(method)){
  84. String id = request.getParameter( "id");
  85. String name = request.getParameter( "name");
  86. String address = request.getParameter( "address");
  87. String tel = request.getParameter( "tel");
  88. String dishes = request.getParameter( "dishes");
  89. Good good = new Good(Integer.valueOf(id),name,address,tel,dishes);
  90. goodDao.update(good);
  91. //调用dao的查询方法,返回一个List
  92. List<Good> goods = goodDao.queryByName(keywords);
  93. request.setAttribute( "list", goods);
  94. request.getRequestDispatcher( "goods.jsp").forward(request, response);
  95. } else{
  96. //调用dao的查询方法,返回一个List
  97. List<Good> goods = goodDao.queryByName(keywords);
  98. request.setAttribute( "list", goods);
  99. request.getRequestDispatcher( "goods.jsp").forward(request, response);
  100. }
  101. }
  102. }

5.在JSP页面获取Servlet里面传过来的数据


  
  1. <%@ page language="java" contentType="text/html; charset=utf-8"
  2. pageEncoding= "utf-8" import= "java.util.ArrayList,com.ambow.pojo.Good,
  3. com.ambow.pojo.User,com.ambow.utils.PageBeanUtils"%>
  4. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  5. <!DOCTYPE html>
  6. <html>
  7. <head>
  8. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  9. <title>外卖系统的搜索功能 </title>
  10. </head>
  11. <body>
  12. <form action="QueryServlet?method=search" method="POST">
  13. <input type="text" name="kw"/> <input type="submit" value="搜索"/> <a href=" ">添加商家 </a >
  14. <table border="1">
  15. <tr> <th>商家店名 </th> <th>商家地址 </th> <th>商家电话 </th> <th>经营菜品 </th> <th colspan="2">编辑 </th> </tr>
  16. <c:forEach items="${pg.pageData}" var="g">
  17. <tr> <td>${g.name} </td> <td>${g.address} </td> <td>${g.tel} </td> <td>${g.dishes} </td>
  18. <td> <a href="QueryServlet?method=queryById&id=${g.id}">修改 </a > </td>
  19. <td> <a href="QueryServlet?method=delete&id=${g.id}" onClick="return confirm('确认删除本条数据吗?');">删除 </a > </td> </tr>
  20. </c:forEach>
  21. </table>
  22. <a href="QueryServlet?method=search&curPage=${pg.firstPage}">首页 </a >
  23. <a href="QueryServlet?method=search&curPage=${pg.currentPage - 1}">上一页 </a >
  24. <a href="QueryServlet?method=search&curPage=${pg.currentPage + 1}">下一页 </a >
  25. <a href="QueryServlet?method=search&curPage=${pg.lastPage}">尾页 </a >
  26. 当前第${pg.currentPage}页/共${pg.totalPage}页
  27. 每页显示${pg.pageSize}条
  28. </form>
  29. </body>
  30. </html>

 


转载:https://blog.csdn.net/kuailexiaohan/article/details/109845618
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场