JDBC在javaweb中的应用之分页数据查询

来源:互联网 发布:爱名网域名过户步骤 编辑:程序博客网 时间:2024/06/07 11:07

 

分页查询

分页查询是java web开发中经常使用到的技术。在数据库中数据量非常大的情况下,不适合将所有的数据全部显示到一个页面中,同时为了节约程序以及数据库的资源,就需要对数据进行分页查询操作。
通过JDBC实现分页的方法比较多,而且不同的数据库机制其分页的方式也不同,这里我们介绍典型的两个分页方法。
1.通过ResultSet的光标实现分页

该分页方法可以在各种数据库之间通用,但是带来的缺点是占用了大量的资源,不适合在数据库大的情况下使用。
2.通过数据库机制进行分页

很多数据库都会提供这种分页机制,例如SQLServer中就提供了top关键字,mysql数据库中提供了limit关键字,用这些关键字都可以设置数据返回的记录数。使用这种分页查询方式可以减少数据库的资源开销,提高程序效率,但是缺点是只适应于一种数据库。

注:因为第一种不适合在数据量大的情况下使用,所以在实际开发中也不使用该方式来查询数据,我们只对第二种方式做介绍

例:通过mysql的数据分页机制来实现商品信息的分页查询功能,并将信息显示在jsp页面中

(1)创建一个商品信息属性Product类,用来保存商品属性,此类为JavaBean

 

 1 package com.bean; 2  3 public class Product { 4    public static final int PAGE_SIZE = 2; 5    //编号 6    private int id; 7    //名称 8    private String name; 9    //价格10    private double price;11    //数量12    private int num;13    //单位14    private String unit;15 public int getId() {16     return id;17 }18 public void setId(int id) {19     this.id = id;20 }21 public String getName() {22     return name;23 }24 public void setName(String name) {25     this.name = name;26 }27 public double getPrice() {28     return price;29 }30 public void setPrice(double price) {31     this.price = price;32 }33 public int getNum() {34     return num;35 }36 public void setNum(int num) {37     this.num = num;38 }39 public String getUnit() {40     return unit;41 }42 public void setUnit(String unit) {43     this.unit = unit;44 }45 }
Product.java代码

 

java中一般静态常量我们采用大写字母表示。这是一种java书写规范

(2)创建BookDao类,此类中主要实现了getConnection()方法连接到数据库的操作以及分页查询所有信息的方法find(int page)、查询记录总数的方法findCount()。代码如下:

  1 package com.bean;  2 import java.sql.Connection;  3 import java.sql.DriverManager;  4 import java.sql.PreparedStatement;  5 import java.sql.ResultSet;  6 import java.sql.SQLException;  7 import java.sql.Statement;  8 import java.util.ArrayList;  9 import java.util.List; 10 public class BookDao { 11     public Connection getConnection() { 12         //数据库连接 13         Connection conn = null; 14         try { 15             //加载数据库驱动,注册到驱动管理器 16             Class.forName("com.mysql.jdbc.Driver"); 17             //数据库连接字符串 18             String url = "jdbc:mysql://localhost:3306/db_database10"; 19             //数据库用户名 20             String username = "root"; 21             //数据库密码 22             String password = "123456"; 23             //创建Connection连接 24             conn = DriverManager.getConnection(url,username,password); 25              26         }catch(ClassNotFoundException e) { 27             e.printStackTrace(); 28         }catch(SQLException e) { 29             e.printStackTrace(); 30         } 31         return conn; 32     } 33      34     /** 35      * 分页查询所有信息 36      * @param page 页数 37      * @return List<Product> 38      */ 39     public List<Product> find(int page){ 40          41         //创建List 42         List<Product> list = new ArrayList<Product>(); 43         //获取数据库连接 44         Connection conn = getConnection(); 45         //分页查询的SQL语句 46         String sql = "select * from tb_product order by id desc limit ?,?"; 47         try { 48             //获取PreparedStatement 49             PreparedStatement ps = conn.prepareStatement(sql); 50             //SQL语句中的第1个参数赋值 51             ps.setInt(1, (page - 1) * Product.PAGE_SIZE); 52             //对SQL语句中的第2个参数赋值 53             ps.setInt(2, Product.PAGE_SIZE); 54             //执行查询操作 55             ResultSet rs = ps.executeQuery(); 56             //光标向后移动,并判断是否有效 57             while(rs.next()) { 58                 //实例化Product 59                 Product p = new Product(); 60                 //对id属性赋值 61                 p.setId(rs.getInt("id")); 62                 //对name属性赋值 63                 p.setName(rs.getString("name")); 64                 //对num属性赋值 65                 p.setNum(rs.getInt("num")); 66                 //对price属性赋值 67                 p.setPrice(rs.getDouble("price")); 68                 //对unit属性赋值 69                 p.setUnit(rs.getString("unit")); 70                 //将Product添加到List结合中 71                 list.add(p); 72             } 73             //关闭ResultSet 74             rs.close(); 75             //关闭PreparedStatement 76             ps.close(); 77             //关闭Connection 78             conn.close(); 79         }catch(SQLException e) { 80             e.printStackTrace(); 81         } 82         return list; 83          84     } 85     /** 86      * 查询记录总数 87      * @return count记录数 88      */ 89     public int findCount() { 90         //总记录数 91         int count = 0; 92         //获取数据库连接 93         Connection conn = getConnection(); 94         //查询总记录数SQL语句 95         String sql = "select count(*) from tb_product"; 96         try { 97             //创建Statement 98             Statement stmt = conn.createStatement(); 99             //查询并获取ResultSet100             ResultSet rs = stmt.executeQuery(sql);101             //光标向后移动,并判断是否有效102             if(rs.next()) {103                 //取出id字段的值对总记录赋值104                 count = rs.getInt(1);105             }106             //关闭ResultSet107             rs.close();108             //关闭Connection109             conn.close();110         }catch(SQLException e) {111             e.printStackTrace();112         }113         //返回总记录114         return count;115     }116     117 }
BookDao.java代码

说明:MySQL中分页查询机制关键词limit的说明

limit arg1,arg2

参数说明:

arg1:用于指定查询记录的起始位置。

arg2:用于指定查询数据所返回的记录数。

(3)创建一个Servlet ,类名为FindServlet类此类继承了HttpServlet,主要实现了doGet()方法,接收和处理jsp页面中提交来的表单数据,代码如下:

 1 package com.servlet; 2 import java.io.IOException; 3 import java.util.List; 4 import javax.servlet.ServletException; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import com.bean.BookDao; 9 import com.bean.Product;10 11 public class FindServlet extends HttpServlet {12     private static final long serialVersionUID = 1L;13     14     protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{15         //当前页码16         int currPage = 1;17         //判断传递页码是否有效18         if(request.getParameter("page") != null) {19             //对当前页码赋值20             currPage = Integer.parseInt(request.getParameter("page"));21         }22         //实例化ProductDao23         BookDao dao = new BookDao();24         //查询所有商品信息25         List<Product> list = dao.find(currPage);26         //将list放置到request中27         request.setAttribute("list", list);28         //总页数29         int pages;30         //查询总记录数31         int count = dao.findCount();32         //计算总页数33         if(count % Product.PAGE_SIZE == 0) {34             //对总页数赋值35             pages = count / Product.PAGE_SIZE;36         }else {37             //对总页数赋值38             pages = count / Product.PAGE_SIZE + 1;39         }40         //实例化StringBuffer41         StringBuffer sb = new StringBuffer();42         //通过循环构建分页条43         for(int i=1;i<=pages;i++) {44             //判断是否为当前页45             if(i == currPage) {46                 //构建分页条47                 sb.append("[" + i + "]");48             }else {49                 //构建分页条50                 sb.append("<a href='FindServlet?page=" + i + "'>" + i + "</a>");51             }52             sb.append(" ");53         }54         //将分页条的字符串放置到request中55         request.setAttribute("bar", sb.toString());56         //转发到product_list.jsp页面57         request.getRequestDispatcher("product_list.jsp").forward(request, response);58     }59 }
FindServlet.java代码

注意:分页条在JSP页面中是动态内容,每次查看新页面都要重新构造,所以,实例中将分页的构造放置到Servlet中,以简化JSP页面的代码。

在获取查询结果集List与分页条后,FindServlet1分别将这两个对象放置到request中,将请求转发到product_list.jsp页面做出显示

(4)创建product_list.jsp页面,通过查询List结果集对象来将结果显示在页面

 1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2     pageEncoding="UTF-8"%> 3 <%@ page import="java.util.List" %> 4 <%@ page import="com.bean.Product" %> 5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 6 <html> 7 <head> 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 9 <title>所有商品信息</title>10 </head>11 <body>12     <table align="center" width="450px" border="1" height="180px" bordercolor="white" bgcolor="black" cellpadding="1">13         <tr bgcolor="white">14             <td align="center" colspan="5">15                 <h2>所有商品信息</h2>16             </td>17         </tr>18         <tr align="center" bgcolor="#e1ffc1">19             <td><b>ID</b></td>20             <td><b>商品名称</b></td>21             <td><b>价格</b></td>22             <td><b>数量</b></td>23             <td><b>单位</b></td>24         </tr>25         <%26         List<Product> list = (List<Product>)request.getAttribute("list");27         for(Product p:list){28         %>29         <tr align="center" bgcolor="white">30             <td><%=p.getId() %></td>31             <td><%=p.getName() %></td>32             <td><%=p.getPrice() %></td>33             <td><%=p.getNum() %></td>34             <td><%=p.getUnit() %></td>35         </tr>36         <%37         }38         %>39         <tr>40             <td align="center" colspan="5" bgcolor="white">41                 <%=request.getAttribute("bar") %>42             </td>43         </tr>44         45     </table>46 </body>47 </html>
product_list.jsp代码

(5)创建index.jsp页面,在该页面中创建了一个指向FindServlet类的超链接,用来查询商品信息

 1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2     pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>分页数据查询</title> 8 </head> 9 <body>10     <a href="FindServlet">查看所有商品信息</a>11 </body>12 </html>
index.jsp代码

(6)web.xml中的Servlet配置信息如下:

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <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_3_0.xsd" id="WebApp_ID" version="3.0"> 3   <display-name>Test2</display-name> 4   <welcome-file-list> 5     <welcome-file>index.html</welcome-file> 6     <welcome-file>index.htm</welcome-file> 7     <welcome-file>index.jsp</welcome-file> 8     <welcome-file>default.html</welcome-file> 9     <welcome-file>default.htm</welcome-file>10     <welcome-file>default.jsp</welcome-file>11   </welcome-file-list>12   <servlet>13       <servlet-name>FindServlet</servlet-name>14       <servlet-class>com.servlet.FindServlet</servlet-class>15   </servlet>16   <servlet-mapping>17       <servlet-name>FindServlet</servlet-name>18       <url-pattern>/FindServlet</url-pattern>19   </servlet-mapping>20 </web-app>
web.xml代码

配置完成后运行项目结果: