• web开发之分页案例jQuery&BootStrap


    考虑到用户数据量大,为了用户有更好的体验。一般情况下,数据在展示时都会进行分页操作。分页有两种。1.物理分页 :使用数据库本身提供的分页操作来完成数据查询,查询到的就是当前页的信息。例如mysql可以使用limit ,oracle数据库可以使用rownum来完成。这种方案的优点是性能比较好,但是它存在不通用问题。2.逻辑分页 :它是利用数据库的游标来操作 (将数据库所有数据都查询出来,存储在内存中),性能比较低,但是它通用。现在开发中一般使用的比较多的是物理分页。

    涉及到的技术点:

    1.前端使用bootstrap的分页组件来完成数据分页显示。

    2.服务器端使用javaee经典三层架构

    3.使用c3p0连接池,dbutils来完成数据库操作。

    javaee三层架构如下:

    Web层:它主要包含的关于javaweb相关操作,例如request,response,session对象操作,它调用业务层来实现具体的功能。

    业务层(service层):它主要是业务逻辑操作,它不包含web常用对象,它只是java代码。

    数据访问层(dao层):它主要是与数据库进行交互,完成crud操作。

    注意:在使用bootstrap的分页组件时,需要导入相关的css文件与js文件,并且bootstrap它依赖于jquery,在导入bootstrap的js文件前要导入jquery的js文件,并且它的版本要求必须是1.9.1以上版本.

    1)MySQL5.7,创建数据库,创建表,并插入一些记录,具体如下:

    1. CREATE DATABASE if not exists test;
    2. USE test;
    3. CREATE TABLE if not exists product(
    4. id INT PRIMARY KEY AUTO_INCREMENT,
    5. NAME VARCHAR(20),
    6. COUNT INT,
    7. price DOUBLE
    8. );
    9. INSERT INTO product VALUES(NULL,'电视机',100,2000);
    10. INSERT INTO product VALUES(NULL,'洗衣机',200,1000);
    11. INSERT INTO product VALUES(NULL,'空调',300,3000);
    12. INSERT INTO product VALUES(NULL,'投影仪',50,2000);
    13. INSERT INTO product VALUES(NULL,'HP电脑',100,4000);
    14. INSERT INTO product VALUES(NULL,'苹果手机',100,5000);
    15. INSERT INTO product VALUES(NULL,'缝纫机',100,2000);
    16. INSERT INTO product VALUES(NULL,'小米盒子',100,2200);
    17. INSERT INTO product VALUES(NULL,'饮水机',100,2000);
    18. INSERT INTO product VALUES(NULL,'净水器',100,2000);
    19. INSERT INTO product VALUES(NULL,'电暖器',100,2000);

    2)引入相关的jar包,包括:C3p0连接池jar , Dbutils, json处理的相关jar包,mysql的驱动jar包。

     3)创建服务器项目结构

     4)编写数据库表对应的实体类,同时创建一个Bean类,用于对页面相关信息进行封装。

    1. public class Product {
    2. private int id ;
    3. private String name ;
    4. private int count ;
    5. private double price ;
    6. public int getId() {
    7. return id;
    8. }
    9. public void setId(int id) {
    10. this.id = id;
    11. }
    12. public String getName() {
    13. return name;
    14. }
    15. public void setName(String name) {
    16. this.name = name;
    17. }
    18. public int getCount() {
    19. return count;
    20. }
    21. public void setCount(int count) {
    22. this.count = count;
    23. }
    24. public double getPrice() {
    25. return price;
    26. }
    27. public void setPrice(double price) {
    28. this.price = price;
    29. }
    30. @Override
    31. public String toString() {
    32. return "Product{" +
    33. "id=" + id +
    34. ", name='" + name + '\'' +
    35. ", count=" + count +
    36. ", price=" + price +
    37. '}';
    38. }
    39. }
    1. import java.util.List;
    2. public class PageBean {
    3. private int pageNo ; //页码数
    4. private int pageSize ; //每页显示的条数
    5. private int totalPage ; //总页数
    6. private int totalCount ; //总条数
    7. private List content ; //当前页显示的数据
    8. public int getPageNo() {
    9. return pageNo;
    10. }
    11. public void setPageNo(int pageNo) {
    12. this.pageNo = pageNo;
    13. }
    14. public int getPageSize() {
    15. return pageSize;
    16. }
    17. public void setPageSize(int pageSize) {
    18. this.pageSize = pageSize;
    19. }
    20. public int getTotalPage() {
    21. return totalPage;
    22. }
    23. public void setTotalPage(int totalPage) {
    24. this.totalPage = totalPage;
    25. }
    26. public int getTotalCount() {
    27. return totalCount;
    28. }
    29. public void setTotalCount(int totalCount) {
    30. this.totalCount = totalCount;
    31. }
    32. public List getContent() {
    33. return content;
    34. }
    35. public void setContent(List content) {
    36. this.content = content;
    37. }
    38. @Override
    39. public String toString() {
    40. return "PageBean{" +
    41. "pageNo=" + pageNo +
    42. ", pageSize=" + pageSize +
    43. ", totalPage=" + totalPage +
    44. ", totalCount=" + totalCount +
    45. ", content=" + content +
    46. '}';
    47. }
    48. }

    5)创建一个JdbcUtils 工具类,在使用dbutils的QueryRunner进行crud时需要Connection对象或DataSource对象,工具类代码如下:

    1. import com.mchange.v2.c3p0.ComboPooledDataSource;
    2. import javax.sql.DataSource;
    3. import java.sql.Connection;
    4. import java.sql.SQLException;
    5. public class JDBCUtils {
    6. private static ComboPooledDataSource dataSource = new ComboPooledDataSource() ;
    7. public static DataSource getDataSource(){
    8. return dataSource ;
    9. }
    10. public static Connection getConnection() throws SQLException {
    11. return dataSource.getConnection() ;
    12. }
    13. }

    5)dao层创建接口和实现类

    1. import coms.domain.Product;
    2. import java.sql.SQLException;
    3. import java.util.List;
    4. public interface ProductDao {
    5. List findAll(int pageNo, int pageSize) throws SQLException;
    6. int findAllCount() throws SQLException;
    7. }
    1. import coms.utils.JDBCUtils;
    2. import coms.domain.Product;
    3. import org.apache.commons.dbutils.QueryRunner;
    4. import org.apache.commons.dbutils.handlers.BeanListHandler;
    5. import org.apache.commons.dbutils.handlers.ScalarHandler;
    6. import java.sql.SQLException;
    7. import java.util.List;
    8. public class ProductDaoImpl implements ProductDao {
    9. @Override
    10. public List findAll(int pageNo, int pageSize) throws SQLException {
    11. QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource()) ;
    12. return queryRunner.query("select * from product limit ?,?", new BeanListHandler(Product.class),(pageNo-1)*pageSize,pageSize) ;
    13. }
    14. @Override
    15. public int findAllCount() throws SQLException {
    16. QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource()) ;
    17. Long l = (Long) queryRunner.query("select count(*) from product", new ScalarHandler());
    18. return l.intValue() ;
    19. }
    20. }

    6)业务层(service)调用接口中的方法对获取的数据进行封装,并返回bean对象。

    1. import coms.dao.ProductDao;
    2. import coms.dao.ProductDaoImpl;
    3. import coms.domain.PageBean;
    4. import coms.domain.Product;
    5. import java.sql.SQLException;
    6. import java.util.List;
    7. public class ProductService {
    8. public PageBean findAll(int pageNo, int pageSize) throws SQLException {
    9. ProductDao productDao = new ProductDaoImpl() ;
    10. List ps = productDao.findAll(pageNo,pageSize) ; //分页的产品信息
    11. //将分页的数据信息封装到PageBean中
    12. PageBean productPageBean = new PageBean() ;
    13. productPageBean.setPageNo(pageNo);
    14. productPageBean.setPageSize(pageSize);
    15. productPageBean.setContent(ps);
    16. //总条数
    17. int totalCount = productDao.findAllCount() ;
    18. //总页数
    19. int totalPage = (int) Math.ceil(1.0 * totalCount / pageSize);
    20. productPageBean.setTotalCount(totalCount);
    21. productPageBean.setTotalPage(totalPage);
    22. return productPageBean ;
    23. }
    24. }

    7)web层响应浏览器的请求,并将封装的bean转换成json回传到浏览器。

    1. import com.alibaba.fastjson.JSONObject;
    2. import coms.domain.PageBean;
    3. import coms.domain.Product;
    4. import coms.service.ProductService;
    5. import javax.servlet.ServletException;
    6. import javax.servlet.annotation.WebServlet;
    7. import javax.servlet.http.HttpServlet;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import java.io.IOException;
    11. import java.sql.SQLException;
    12. import java.util.List;
    13. @WebServlet(name = "ProductServlet")
    14. public class ProductServlet extends HttpServlet {
    15. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    16. doGet(request,response);
    17. }
    18. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    19. response.setCharacterEncoding("utf-8");
    20. request.setCharacterEncoding("utf-8");
    21. ProductService productService = new ProductService() ;
    22. int pageNo = Integer.parseInt(request.getParameter("pageNo")) ;
    23. int pageSize = Integer.parseInt(request.getParameter("pageSize")) ;
    24. try {
    25. PageBean pageBean = productService.findAll(pageNo,pageSize) ;
    26. //将从数据库查询的数据转换成json响应到浏览器
    27. String json = JSONObject.toJSONString(pageBean) ;
    28. response.getWriter().write(json);
    29. } catch (SQLException e) {
    30. e.printStackTrace();
    31. }
    32. }
    33. }

    html页面根据jQuery和Bootstrap添加表格和分页条,根据得到的分页信息,进行处理。

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Titletitle>
    6. <link rel="stylesheet" href="/servlet_war_exploded/bootstrap/css/bootstrap.css">
    7. <script src="/servlet_war_exploded/bootstrap/js/jquery-1.11.3.js">script>
    8. <script src="/servlet_war_exploded/bootstrap/js/bootstrap.js">script>
    9. <script type="text/javascript">
    10. var pageNo = 1 ; //页码
    11. var pageSize = 5 ; //每页显示的条数
    12. var totalCount = 10 ; //总条数
    13. var totalPage = 100 ; //总页数
    14. $(function() {
    15. skipPage(pageNo);
    16. });
    17. function skipPage(pageNum) {
    18. pageNo = pageNum;
    19. //页面加载完成后向服务器发送请求,将请求得到的数据显示到表格中
    20. var url = "/servlet_war_exploded/product" ;
    21. $.post(url,{"pageNo":pageNo,"pageSize":pageSize},function (data) {
    22. var obj1 = eval(data) ;
    23. var obj = obj1.content ;
    24. //将页码 每页条数 总条数,总页数与服务器响应的数据同步
    25. pageNo = obj1.pageNo;
    26. pageSize = obj1.pageSize;
    27. totalPage = obj1.totalPage;
    28. totalCount = obj1.totalCount;
    29. var html = "" ;
    30. for(var i=0; i
    31. html += "<tr>" ;
    32. html += "<td>" + obj[i].id + "td><td>" + obj[i].name + "td><td>" + obj[i].count + "td><td>" + obj[i].price + "td>" ;
    33. html += "tr>" ;
    34. }
    35. //展示分页条数据
    36. var pageMsg = "<ul class='pagination pagination-sm'>";
    37. //处理上一页操作
    38. if (pageNo == 1) {
    39. //上一页操作不可以点击
    40. pageMsg += "<li class='disabled'><a href='#'>«a>li>";
    41. } else {
    42. pageMsg += "<li><a href='javascript:void(0)' onclick=skipPage("+ (pageNo - 1) +")>«a>li>";
    43. }
    44. for (var i = 0; i < totalPage; i++) {
    45. //判断页码与(i+1)是否一致,一致就代表当前页码要高亮显示
    46. if (i + 1 == pageNo) {
    47. pageMsg += "<li class='active'><a href='javascript:void(0)' onclick='skipPage(" + (i + 1) + ")'>" + (i + 1) + " <span class='sr-only'>(current)span>a>li>";
    48. } else {
    49. pageMsg += "<li><a href='javascript:void(0)' onclick='skipPage(" + (i + 1) + ")'>" + (i + 1) + "a>li>";
    50. }
    51. }
    52. //处理下一页操作
    53. if (pageNo == totalPage) {
    54. pageMsg += "<li class='disabled'><a href='#'>»a>li>";
    55. } else {
    56. pageMsg += "<li><a href='javascript:void(0)' onclick='skipPage(" + (pageNo + 1) + ")')>»a>li>";
    57. }
    58. pageMsg += "ul>";
    59. //清空table中的数据,让它恢复成原始状态
    60. $("#tab").html("<tr><td>序号td> <td>名称td><td>数量td> <td>价格td> tr><tr><td colspan='4'><nav id='n'>nav>td>tr>");
    61. $("#n").append(pageMsg);
    62. $("#tab tr:nth-child(1)").after(html);
    63. },"json") ;
    64. };
    65. script>
    66. <style type="text/css">
    67. div {
    68. width: 70%;
    69. margin-left: 200px;
    70. margin-top: 100px;
    71. }
    72. style>
    73. head>
    74. <body>
    75. <div align="center">
    76. <table class="table table-bordered" id="tab">
    77. <tr>
    78. <td>序号td>
    79. <td>名称td>
    80. <td>数量td>
    81. <td>价格td>
    82. tr>
    83. <tr>
    84. <td colspan="4">
    85. <nav id="n">nav>
    86. td>
    87. tr>
    88. table>
    89. div>
    90. body>
    91. html>

    8)需要在web.xml中配置servlet。

    1. "1.0" encoding="UTF-8"?>
    2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    5. version="4.0">
    6. <servlet>
    7. <servlet-name>ProductServletservlet-name>
    8. <servlet-class>coms.web.ProductServletservlet-class>
    9. servlet>
    10. <servlet-mapping>
    11. <servlet-name>ProductServletservlet-name>
    12. <url-pattern>/producturl-pattern>
    13. servlet-mapping>
    14. web-app>

    9)使用连接池的时候需要配置mysql信息,c3p0-config.xml文件配置如下:

    1. "1.0" encoding="UTF-8"?>
    2. <c3p0-config>
    3. <default-config>
    4. <property name="driverClass">com.mysql.jdbc.Driverproperty>
    5. <property name="jdbcUrl">jdbc:mysql:///testproperty>
    6. <property name="user">rootproperty>
    7. <property name="password">123456property>
    8. <property name="initialPoolSize">5property>
    9. <property name="minPoolSize">5property>
    10. <property name="maxPoolSize">20property>
    11. default-config>
    12. c3p0-config>

    分页效果如下:

  • 相关阅读:
    人才网招聘网程序人才招聘系统/招聘APP/H5/求职招聘兼职/招聘企业职位求职招聘小程序
    关于近期IP-Guard新版本客户端重复发送邮件的问题处理说明
    windows不能修改hosts?有这篇文章就够了
    图数据 3D 可视化在 Explorer 中的应用
    【对比】Gemini:听说GPT-4你小子挺厉害
    Gitee 图床被屏蔽后,我搭建了一个文件系统并封装成轮子开源
    6.3、Flink数据写入到MySQL
    PHP如何实现动态代理IP
    应对数据安全典型薄弱点,这家医院“外防内控”筑牢屏障
    详解【计算机类&面试真题】军队文职考试——第8期:OSI的七层模型 | 数据通信的三种方式 | 通信网络的检查方法,附Python进行网络连通性检查、带宽测试、端口扫描、链路质量测试、安全性扫描
  • 原文地址:https://blog.csdn.net/nuist_NJUPT/article/details/126522929