Java Web中分页的实现 - 技术分享 - 志盟培训
首页技术分享 Java Web中分页的实现

Java Web中分页的实现

更新时间:2017-06-20      作者:陆老师       阅读:777

随着Web应用的数据越来越多,很多情况下我们在一个页面中无法显示全部内容,或者说即使显示全,那用户也一直要拖动滚动条来实现数据的阅读,很不方便。对此,我们一般有两种解决方案。方案一、Ajax异步加载,当用户感兴趣,想要继续阅读后面内容时,我们再异步去数据库取下一页数据,不刷新整个页面。方案二、我们用分页功能,显示页码,用户可以点击下一页,上一页,或者具体的某一页。第二种方案,使用的比较广泛,所以我们就一起来学习下Java Web应用中的分页的实现过程。

首先,我们需要准备Java Web开发环境。JDK8,Tomcat7,Maven3,MySQL5.7,Alibaba的数据源druid。

这里主要是项目的pom.xml文件,如下:


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.jabari</groupId>

<artifactId>mvn-web</artifactId>

<packaging>war</packaging>

<version>0.0.1-SNAPSHOT</version>

<name>mvn-web Maven Webapp</name>

<url>http://maven.apache.org</url>

<properties>

<!-- 文件拷贝时的编码 -->

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<!-- 编译时的编码 -->

<maven.compiler.encoding>UTF-8</maven.compiler.encoding>

<junit.version>4.11</junit.version>

<servlet-api.version>3.1.0</servlet-api.version>

<jsp-api.version>2.3.1</jsp-api.version>

<mysql-connector-java.version>6.0.5</mysql-connector-java.version>

<jdk.version>1.8</jdk.version>

<tomcat7-plugin.version>2.2</tomcat7-plugin.version>

<mvn-compiler-plugin.version>3.5.1</mvn-compiler-plugin.version>

<tomcat.port>80</tomcat.port>

<jstl.version>1.2.5</jstl.version>

<commons-fileupload.version>1.3.1</commons-fileupload.version>

<c3p0.version>0.9.1.2</c3p0.version>

<druid.version>1.0.29</druid.version>

<dbutils.version>1.6</dbutils.version>



<log4j.version>1.2.17</log4j.version>

<commons-logging.version>1.2</commons-logging.version>

<slf4j.version>1.7.6</slf4j.version>

         <logback.version>1.1.2</logback.version>

<spring.version>4.3.6.RELEASE</spring.version>

<mybatis.version>3.4.2</mybatis.version>

<mybatis-spring.version>1.2.5</mybatis-spring.version>

<fastjson.version>1.2.6</fastjson.version>

<httpclient.version>4.5</httpclient.version>

<commons-lang.version>2.6</commons-lang.version>

<commons-codec>1.9</commons-codec>

<jackson-mapper-asl.version>1.9.13</jackson-mapper-asl.version>

</properties>

<dependencies>

         <!-- Servlet API -->

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>javax.servlet-api</artifactId>

<version>${servlet-api.version}</version>

<scope>provided</scope>

</dependency>

<!-- JSP API -->

         <dependency>

         <groupId>javax.servlet.jsp</groupId>

         <artifactId>javax.servlet.jsp-api</artifactId>

<version>${jsp-api.version}</version>

         <scope>provided</scope>

         </dependency>

        

         <!--  Junit  -->

         <dependency>

                   <groupId>junit</groupId>

         <artifactId>junit</artifactId>

         <version>${junit.version}</version>

         <scope>test</scope>

         </dependency>

        

        

         <!-- Mysql - driver -->

         <dependency>


                   <groupId>mysql</groupId>

         <artifactId>mysql-connector-java</artifactId>

         <scope>runtime</scope>

         </dependency>

        

         <!-- taglibs-standard-jstlel -->

         <dependency>

         <groupId>org.apache.taglibs</groupId>

         <artifactId>taglibs-standard-jstlel</artifactId>

         </dependency>

        

         <!-- 文件上传 依赖 -->

         <dependency>

                   <groupId>commons-fileupload</groupId>

                   <artifactId>commons-fileupload</artifactId>

         </dependency>

        

         <dependency>

                   <groupId>log4j</groupId>

                   <artifactId>log4j</artifactId>

                   <version>${log4j.version}</version>

         </dependency>

        

         <dependency>

         <groupId>com.alibaba</groupId>

         <artifactId>druid</artifactId>

         </dependency>

        

         <dependency>

         <groupId>commons-dbutils</groupId>

         <artifactId>commons-dbutils</artifactId>

         </dependency>

        

         <dependency>

         <groupId>ch.qos.logback</groupId>

         <artifactId>logback-access</artifactId>

         <version>${logback.version}</version>

         </dependency>

         <dependency>

         <groupId>ch.qos.logback</groupId>

         <artifactId>logback-classic</artifactId>

         <version>${logback.version}</version>

         </dependency>


         

         <dependency>

                   <groupId>com.alibaba</groupId>

                   <artifactId>fastjson</artifactId>

         </dependency>

         <dependency>

                   <groupId>org.codehaus.jackson</groupId>

                   <artifactId>jackson-mapper-asl</artifactId>

         </dependency>

         <dependency>

                   <groupId>commons-lang</groupId>

                   <artifactId>commons-lang</artifactId>

         </dependency>

         <dependency>

                   <groupId>org.apache.httpcomponents</groupId>

                   <artifactId>httpclient</artifactId>

                   <exclusions>

                            <exclusion>

                                     <groupId>commons-codec</groupId>

                                     <artifactId>commons-codec</artifactId>

                            </exclusion>

                   </exclusions>

         </dependency>

        

         <!-- mybatis依赖 -->

         <dependency>

                   <groupId>org.mybatis</groupId>

                   <artifactId>mybatis</artifactId>

         </dependency>

         <!-- mybatisspring整合 依赖 -->

         <dependency>

                   <groupId>org.mybatis</groupId>

                   <artifactId>mybatis-spring</artifactId>

         </dependency>

        

         <!-- Spring 依赖 -->

<dependency>

         <groupId>org.springframework</groupId>

         <artifactId>spring-context</artifactId>

</dependency>

<dependency>

         <groupId>org.springframework</groupId>


         <artifactId>spring-webmvc</artifactId>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context-support</artifactId>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-aop</artifactId>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-aspects</artifactId>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-tx</artifactId>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-jdbc</artifactId>

</dependency>

<dependency>

                   <groupId>org.springframework</groupId>

                   <artifactId>spring-test</artifactId>

         </dependency>

        

</dependencies>

<!-- 依赖管理: 只管理依赖,并不引入依赖。

         当需要用到哪个的时候再复制到上面使用。 -->

<dependencyManagement>

         <dependencies>

        

                   <dependency>

                            <groupId>c3p0</groupId>

                            <artifactId>c3p0</artifactId>

                            <version>${c3p0.version}</version>

                   </dependency>

                  

                   <dependency>

                   <groupId>com.alibaba</groupId>



                   <artifactId>druid</artifactId>

                   <version>${druid.version}</version>

                   </dependency>

        

                   <dependency>

                            <groupId>com.alibaba</groupId>

                            <artifactId>fastjson</artifactId>

                            <version>${fastjson.version}</version>

                   </dependency>

                  

                   <dependency>

                   <groupId>commons-dbutils</groupId>

                   <artifactId>commons-dbutils</artifactId>

                   <version>${dbutils.version}</version>

                   </dependency>

                  

                   <dependency>

                            <groupId>org.codehaus.jackson</groupId>

                            <artifactId>jackson-mapper-asl</artifactId>

                            <version>${jackson-mapper-asl.version}</version>

                   </dependency>

        

                   <dependency>

                            <groupId>commons-lang</groupId>

                            <artifactId>commons-lang</artifactId>

                            <version>${commons-lang.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-codec</groupId>

                            <artifactId>commons-codec</artifactId>

                            <version>${commons-codec.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.apache.httpcomponents</groupId>

                            <artifactId>httpclient</artifactId>

                            <version>${httpclient.version}</version>

                            <exclusions>

                                     <exclusion>

                                               <groupId>commons-codec</groupId>

                                               <artifactId>commons-codec</artifactId>

                                     </exclusion>

                            </exclusions>

                   </dependency>

                   


                   <!-- Mysql - driver -->

                   <dependency>

                            <groupId>mysql</groupId>

                   <artifactId>mysql-connector-java</artifactId>

                   <version>${mysql-connector-java.version}</version>

                   <scope>runtime</scope>

                   </dependency>

                  

                   <!-- taglibs-standard-jstlel -->

                   <dependency>

                   <groupId>org.apache.taglibs</groupId>

                   <artifactId>taglibs-standard-jstlel</artifactId>

                   <version>${jstl.version}</version>

                   </dependency>

                  

                   <!-- 文件上传 依赖 -->

                   <dependency>

                            <groupId>commons-fileupload</groupId>

                            <artifactId>commons-fileupload</artifactId>

                            <version>${commons-fileupload.version}</version>

                   </dependency>

                  

                   <!-- mybatis依赖 -->

                   <dependency>

                            <groupId>org.mybatis</groupId>

                            <artifactId>mybatis</artifactId>

                            <version>${mybatis.version}</version>

                   </dependency>

                   <!-- mybatisspring整合 依赖 -->

                   <dependency>

                            <groupId>org.mybatis</groupId>

                            <artifactId>mybatis-spring</artifactId>

                            <version>${mybatis-spring.version}</version>

                   </dependency>

                  

                   <!-- Spring 依赖 -->

<dependency>

         <groupId>org.springframework</groupId>

         <artifactId>spring-context</artifactId>

         <version>${spring.version}</version>

</dependency>

<dependency>

         <groupId>org.springframework</groupId>



         <artifactId>spring-web</artifactId>

         <version>${spring.version}</version>

</dependency>

<dependency>

         <groupId>org.springframework</groupId>

         <artifactId>spring-webmvc</artifactId>

         <version>${spring.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context-support</artifactId>

<version>${spring.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-aop</artifactId>

<version>${spring.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-aspects</artifactId>

<version>${spring.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-tx</artifactId>

<version>${spring.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-jdbc</artifactId>

<version>${spring.version}</version>

</dependency>

<dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-test</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                  

                  

         </dependencies>


</dependencyManagement>

<build>

<finalName>mvn-web</finalName>

<!-- 配置项目的资源文件 -->

<resources>

         <resource>

                   <directory>src/main/java</directory>

         </resource>

         <resource>

                   <directory>src/main/resources</directory>

         </resource>

</resources>

<plugins>

         <!-- 指明Java编译器的版本 -->

         <plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-compiler-plugin</artifactId>

<version>${mvn-compiler-plugin.version}</version>

<configuration>

<source>${jdk.version}</source>

<target>${jdk.version}</target>

</configuration>

</plugin>

         <!-- Tomcat7 的插件 -->

         <plugin>

                            <groupId>org.apache.tomcat.maven</groupId>

                            <artifactId>tomcat7-maven-plugin</artifactId>

                            <version>${tomcat7-plugin.version}</version>

                            <configuration>

                                     <port>${tomcat.port}</port>

                                     <path>/</path>

                            </configuration>

                   </plugin>

</plugins>

</build>

</project>

接着是数据源的配置db_druid.properties,代码如下:

Java Web中分页的实现


核心的应该是Java类,我们分析得知:分页主要是确定4个条件:当前页数,总记录数,每页显示的记录数和每页显示的记录列表。其中还有的总页数,我们有了4个基本条件之后,就可以计算出来。

于是我们抽象出一个PageBean.java类,其代码如下:


package org.jabari.po;

import java.io.Serializable;

import java.util.List;

public class PageBean implements Serializable {

         private static final long serialVersionUID = 4272060441284380825L;

         private long cur = 1;//当前页

         private long totalRecords;//总记录数

         private long totalPage;//总页数

         private long pageSize = 10;//每页记录数

        

         private List<?> list ;//结果列表

         public PageBean(int cur) {

                   super();

                   this.cur = cur;

         }

         public long getTotalRecords() {

                   return totalRecords;

         }

         public void setTotalRecords(long totalRecoreds) {

                   this.totalRecords = totalRecoreds;

         }

         public long getTotalPage() {

                   long calPage = totalRecords%pageSize;

                   if(calPage == 0){

                            totalPage =  totalRecords/pageSize;

                   }else {

                            totalPage = totalRecords/pageSize + 1;

                   }

                   return totalPage;


         }

        

         public void setTotalPage(long totalPage) {

                   this.totalPage = totalPage;

         }

         public long getPageSize() {

                   return pageSize;

         }

         public void setPageSize(long pageSize) {

                   this.pageSize = pageSize;

         }

         public long getCur() {

                   return cur;

         }

         public void setCur(long cur) {

                   this.cur = cur;

         }

         public List<?> getList() {

                   return list;

         }

         public void setList(List<?> list) {

                   this.list = list;

         }

}

对于前端页面,我们只需要传当前页码(必须)、每页的记录数(非必须)给我们Java后台的控制器,就可以了,然后我们控制器根据这两个参数,去MySQL数据库查询,并返回一个PageBean给前端页面,展示分页信息。

前台page.jsp代码:


<%@ page pageEncoding="UTF-8" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

<html lang="en">

         <head>

                   <meta charset="UTF-8">

                   <title>分页演示</title>

                   <link rel="stylesheet" href="css/bootstrap.min.css" />

                   <script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>

                   <script type="text/javascript" src="js/bootstrap.min.js"></script>

                   <script type="text/javascript">

                            function go(pageIndex) {


                                     location.href = "/pagination?pageIndex=" + pageIndex;

                            }

                   </script>

                   <style>

                            #content {

                                     width: 800px;

                                     height: 370px;

                            }

                           

                            #page {

                                     float: right;

                                     width: 800px;

                                     height: 12px;

                            }

                           

                            #page ul li {

                                     float: left;

                                     margin: 3px;

                                     padding: 1px;

                                     background: #ccc;

                                     font-size: 12px;

                            }

                           

                            #page ul li a {

                                     text-decoration: none;

                                     color:black;

                            }

                   </style>

         </head>

         <body>

                   <div id="content">

                            <table width="100%" border="1px" style="border-collapse:collapse;">

                                     <caption>

                                               <h1>用户列表-分页</h1></caption>

                                     <tr>

                                               <th>用户编号</th>

                                               <th>用户名</th>

                                               <th>密码</th>

                                               <th>年龄</th>

                                     </tr>

                                     <c:if test="${not empty page}">

                                               <c:forEach items="${page.list}" var="u">



                                                        <tr>

                                                                 <td>${u.id}</td>

                                                                 <td>${u.name}</td>

                                                                 <td>${u.pwd}</td>

                                                                 <td>${u.age}</td>

                                                        </tr>

                                               </c:forEach>

                                     </c:if>

                            </table>

                   </div>

                   <c:if test="${not empty page and 1 == 2}">

                            <div id="page">

                                     <ul style="list-style:none;">

                                               <li>

                                                        <a href="javascript:go(1)">首页</a>

                                               </li>

                                               <li>

                                                        <c:choose>

                                                                 <c:when test="${page.cur eq 1}">

                                                                           <a href="javascript:void(0)">上一页</a>

                                                                 </c:when>

                                                                 <c:otherwise>

                                                                           <a href="javascript:go(${page.cur - 1})">上一页</a>

                                                                 </c:otherwise>

                                                        </c:choose>

                                               </li>

                                               <c:forEach begin="1" end="${page.totalPage}" var="n">

                                                        <li><a href="javascript:go(${n})">${n}</a></li>

                                              </c:forEach>

                                               <li>

                                                        <c:choose>

                                                                 <c:when test="${page.cur eq page.totalPage}">

                                                                           <a href="javascript:void(0)">下一页</a>

                                                                 </c:when>

                                                                 <c:otherwise>

                                                                           <a href="javascript:go(${page.cur + 1})">下一页</a>

                                                                 </c:otherwise>

                                                        </c:choose>

                                               </li>

                                               <li>

                                                        <a href="javascript:go(${page.totalPage})">尾页</a>

                                               </li>

                                               <li>${page.totalPage}页,共${page.totalRecords}条记录</li>

                                     </ul>

                            </div>

                   </c:if>

                  

                   <c:if test="${not empty page}">

                            <div style="width:600px;" class="center-block">

                                     <ul class="pagination">

                                               <li>

                                                        <a href="javascript:go(1)">首页</a>

                                               </li>

                                               <c:choose>

                                                        <c:when test="${page.cur eq 1}">

                                                                 <li class="disabled">

                                                                           <a href="javascript:void(0)">上一页</a>

                                                                  </li>

                                                        </c:when>

                                                        <c:otherwise>

                                                                 <li>

                                                                           <a href="javascript:go(${page.cur - 1})">上一页</a>

                                                                 </li>

                                                        </c:otherwise>

                                               </c:choose>

                                               <c:forEach begin="1" end="${page.totalPage}" var="n">

                                                        <c:choose>

                                                                 <c:when test="${n eq page.cur}">

                                                                 <li class="active">

                                                                 </c:when>

                                                                 <c:otherwise>

                                                                 <li>

                                                                 </c:otherwise>

                                                        </c:choose>

                                                        <a href="javascript:go(${n})">${n}</a></li>

                                               </c:forEach>

                                              

                                               <c:choose>

                                                        <c:when test="${page.cur eq page.totalPage}">

                                                                 <li class="disabled"><a href="javascript:void(0)">下一页</a></li>

                                                        </c:when>

                                                        <c:otherwise>

                                                                 <li></li><a href="javascript:go(${page.cur + 1})">下一页</a></li>

                                                        </c:otherwise>

                                               </c:choose>

                                               



                                              <li>

                                                        <a href="javascript:go(${page.totalPage})">尾页</a>

                                               </li>

                                               <li style="margin-left:10px;padding-left:10px;"><span>${page.totalPage}页,共${page.totalRecords}条记录</span></li>

                                     </ul>

                            </div>

                   </c:if>

         </body>

</html>


Java后台控制器代码:


package org.jabari.web;

import java.io.IOException;

import java.sql.SQLException;

import java.util.ArrayList;

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 org.apache.commons.dbutils.QueryRunner;

import org.apache.commons.dbutils.handlers.BeanListHandler;

import org.apache.commons.dbutils.handlers.ScalarHandler;

import org.jabari.po.PageBean;

import org.jabari.po.Users;

import com.jabari.demo.utils.DBUtilsHelper;

@WebServlet("/pagination")

public class PaginationController extends HttpServlet {

         @Override

         protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

                   String pageIndexStr  = req.getParameter("pageIndex");

                   int pageIndex = (null == pageIndexStr ? 1 : Integer.parseInt(pageIndexStr));

                   PageBean page = new PageBean(pageIndex);

                   //pageIndex = 6

                  

                   long totalNum = 0;

                   List<Users> userList = new ArrayList<Users>();

                   // DB:  limit (pageIndex-1)*pageSize , pageSize



                   //userList == ......searchDb().....

                   try {

                            DBUtilsHelper dbh = new DBUtilsHelper(); 

                            QueryRunner runner = dbh.getRunner();

                            userList = runner.query("select * from users limit ? , ? ", 

                                    new BeanListHandler<Users>(Users.class),(pageIndex-1)*page.getPageSize(),page.getPageSize());

                  

                           

                            totalNum = runner.query("select count(*) from users", 

                         new ScalarHandler<Long>()); 

                  

                   } catch (SQLException e) {

                            e.printStackTrace();

                   } 

                  

                  

                   page.setList(userList);

                   // DB: select count(*) from user;

                   page.setTotalRecords(totalNum);

                  

                   req.setAttribute("page", page);

                   req.getRequestDispatcher("page.jsp").forward(req, resp);

         }

}

使用maven命令:mvn tomcat7:run运行,最终结果页面如下:


Java Web中分页的实现

Java Web中分页的实现


OK,如果你感兴趣,也不妨试试吧!

在线报名

志盟科技上海招聘

在线报名 联系我们

志盟科技深圳招聘

在线报名 联系我们

志盟科技北京招聘

在线报名 联系我们
联系我们

咨询热线:

咨询 QQ:517578         

就业学员

  • 就业学员

    姓名:郭凡凡 
    院校:阜阳师范学院
    就职:佳戴
    职位:软件工程师
    月薪:10000

  • 就业学员

    姓名:陈祥龙 
    院校:中北大学
    就职:美囤妈妈
    职位:软件工程师
    月薪:9000

  • 就业学员

    姓名:陈建伟
    院校:南昌航空大学
    就职:SONY
    职位:嵌入式工程师
    月薪:8000

×
×
  • *真实姓名
  • *联系手机
  • *上课地址
  •    QQ号码

温馨提示:请保持手机畅通,咨询老师将为您提供专属的一对一报名服务。

×
  • *真实姓名
  • *联系手机
  • *联系邮箱
  • * QQ号码

温馨提示:请保持手机畅通,咨询老师将为您提供专属的一对一的服务。

本站由 宽敬科技——创新企业的建站运营顾问 提供支持