项目结构示意图:

splitPage

|-com.balfish.bean     Goods.java

|-com.balfish.dao       GoodsDao.java

|-com.balfish.servlet   MyServlet.java

|-com.balfish.util        DbConnection.java

|-WEB-INF 

  |-lib 

    |-jstl-1.2.jar

    |-mysql-connector-java-5.1.5-bin.jar

  |-page

    |-myPage.jsp

  |-web.xml

要点: 单例  分层  jstl  limit

访问地址: http://localhost:8080/splitPage/getPage

Goods.java

package com.balfish.bean;

public class Goods {
    private int goodsId;
    private String goodsName;
    private float goodsPrice;
    public int getGoodsId() {
        return goodsId;
    }
    public void setGoodsId(int goodsId) {
        this.goodsId = goodsId;
    }
    public String getGoodsName() {
        return goodsName;
    }
    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }
    public float getGoodsPrice() {
        return goodsPrice;
    }
    public void setGoodsPrice(float goodsPrice) {
        this.goodsPrice = goodsPrice;
    }
}

GoodsDao.java

package com.balfish.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import com.balfish.bean.Goods;
import com.balfish.util.DbConnection;

public class GoodsDao {

    Connection conn;
    PreparedStatement psmt;
    ResultSet rs;

    int pageSize = 5; //每页显示5条数据

    public ResultSet executeQuery(String sql)throws Exception{

        conn =DbConnection.getConnection();
        psmt = conn.prepareStatement(sql);
        rs = psmt.executeQuery(sql);
        return rs;
    }

     //核心还是mysql的limit分页,然后暂存到内存中的ArrayList中
    public ArrayList<Goods> getGoodsList(int currentPage) throws Exception{
        ArrayList<Goods> GoodsList = new ArrayList<Goods>();
        int beginRecord = (currentPage -1) * pageSize;
        int endRecord = currentPage * pageSize;
        rs = executeQuery("select * from goods limit " + beginRecord + "," + endRecord);

        while(rs.next()){
            Goods goods = new Goods();
            goods.setGoodsId(rs.getInt(1));
            goods.setGoodsName(rs.getString(2));
            goods.setGoodsPrice(rs.getFloat(3));
            GoodsList.add(goods);
        }
        return GoodsList;
    } 

    public int getPageCount() throws Exception{
        int total = 0;
        int pageCount = 0;
        rs = executeQuery("select count(*) from goods");

        //得到分页的总页数,由于整数除法结果的取整形式,这里要用一点技巧进行处理
        if(rs.next()){
            total = rs.getInt(1);
            pageCount =(total -1) /pageSize +1;
        }
        return pageCount ;
    }
}

MyServlet.java

package com.balfish.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.balfish.bean.Goods;
import com.balfish.dao.GoodsDao;

public class MyServlet extends HttpServlet{
    public void doGet(HttpServletRequest req , HttpServletResponse resp)
    throws ServletException,IOException{
        doPost(req, resp);
    }

    public void doPost(HttpServletRequest req , HttpServletResponse resp)
            throws ServletException,IOException{

        resp.setContentType("text/html");
        String tmpCurrentPage = req.getParameter("currentPage");

    //下面这几句挺无趣的,容易看的吃力,其实就是如果前面浏览过有页数标记则去读哪个页数,否则从第一页开始
        int currentPage = 1;
        if(tmpCurrentPage != null)
            currentPage = Integer.parseInt(tmpCurrentPage);

        GoodsDao goodsDao = new GoodsDao();
        try{
            ArrayList<Goods> GoodsList = goodsDao.getGoodsList(currentPage);
            //把数据信息放到req作用域中,
            req.setAttribute("GoodsList",GoodsList);
            req.setAttribute("currentPage",currentPage);
            req.setAttribute("pageCount",goodsDao.getPageCount());
            req.getRequestDispatcher("/WEB-INF/page/myPage.jsp").forward(req,resp);

        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public void destroy(){
        super.destroy();
    }

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }
}

DbConnection.java

package com.balfish.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DbConnection {

    //抽象出单例,可作为模板
    private static Connection conn = null;
    private static String url = "jdbc:mysql://localhost/goods_test";
    private static String username ="root";
    private static String password ="";

    private DbConnection(){

    }

    public static Connection getConnection() throws Exception{
        Class.forName("com.mysql.jdbc.Driver");
        if(conn == null)
            conn =  DriverManager.getConnection(url,username,password);
        return conn;
    }
}

sql.txt

create database goods_test;
use goods_test;
create table goods(
    goodsId int,
    goodsName varchar(20),
    goodsPrice float
);

insert into goods values(1,'bag',68.8);
insert into goods values(2,'pen',10.0);
insert into goods values(3,'pencil',2.0);
insert into goods values(4,'mobile',968.8);
insert into goods values(5,'bag',68.8);
insert into goods values(6,'water',1.2);

myPage.jsp

<%@ page language ="java" import ="java.util.*" pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv ="content-type" content="text/html;charset=utf-8">
    </head>

    <body>
        <center>
            <c:if test = "${currentPage >= 1 }">
                <a href ="getPage?curentPage = 1">首页</a>
                <a href ="getPage?currentPage=${ currentPage-1}">上一页</a>
            </c:if>

            <c:if test="${currentPage == 1 }">
                  <a href="getPage?currentPage=${ currentPage+1}">下一页</a>
                  <a href="getPage?currentPage=${ pageCount}">尾页</a>
              </c:if>

              <table width="%80" border="1" height="56" >
                  <tr align ="center">
                      <td>商品编号</td>
                      <td>商品名称</td>
                      <td>商品价格</td>
                  </tr>

                  <c:forEach var="goods" items="${GoodsList}">
<!--  上面的GoodsList后面多些了一个} 就报下面意想不到的错误,查了好久...所以下次jstl表达式使用时一定注意
javax.el.PropertyNotFoundException: Property 'goodsId' not found on type java.lang.String -->
                      <tr align="center">
                     <td>${goods.goodsId }</td>
                     <td>${goods.goodsName }</td>
                     <td>${goods.goodsPrice }</td>
                 </tr>
                  </c:forEach>
              </table>
        </center>
    </body>
</html>

web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"
  metadata-complete="true">

    <servlet>
        <servlet-name>test1</servlet-name>
        <servlet-class>com.balfish.servlet.MyServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>test1</servlet-name>
        <url-pattern>/getPage</url-pattern>
    </servlet-mapping>

</web-app>

运行结果:

地址栏http://localhost:8080/splitPage/getPage?currentPage=2(类似这样~)

首页 上一页 下一页 尾页

商品编号 商品名称 商品价格
1 bag 68.8
2 pen 10.0
3 pencil 2.0
4 mobile 968.8
5 bag 68.8

【jsp 分页】mysql limit方式进行分页的更多相关文章

  1. mysql limit查询(分页查询)探究

    MySQL的Limit子句 LIMIT offset,length Limit子句可以被用于强制 SELECT 语句返回指定的记录数.Limit接受一个或两个数字参数.参数必须是一个整数常量.如果给定 ...

  2. Mysql 分页语句Limit用法

    转载自:http://qimo601.iteye.com/blog/1634748 1.Mysql的limit用法 在我们使用查询语句的时候,经常要返回前几条或者中间某几行数据,这个时候怎么办呢?不用 ...

  3. MySQL分页优化中的“INNER JOIN方式优化分页算法”到底在什么情况下会生效?

    本文出处:http://www.cnblogs.com/wy123/p/7003157.html 最近无意间看到一个MySQL分页优化的测试案例,并没有非常具体地说明测试场景的情况下,给出了一种经典的 ...

  4. mysql limit分页查询效率

    对于有大数据量的mysql表来说,使用LIMIT分页存在很严重的性能问题. 查询从第1000000之后的30条记录: SQL代码1:平均用时6.6秒 SELECT * FROM `cdb_posts` ...

  5. 从官方文档中探索MySQL分页的几种方式及分页优化

    概览 相比于Oracle,SQL Server 等数据库,MySQL分页的方式简单得多了,官方自带了分页语法 limit 语句: select * from test_t LIMIT {[offset ...

  6. mysql的sql分页函数limit使用

    My sql数据库最简单,是利用mysql的LIMIT函数,LIMIT [offset,] rows从数据库表中M条记录开始检索N条记录的语句为: SELECT * FROM 表名称 LIMIT M, ...

  7. 如何优化Mysql千万级快速分页,limit优化快速分页,MySQL处理千万级数据查询的优化方案

    如何优化Mysql千万级快速分页,limit优化快速分页,MySQL处理千万级数据查询的优化方案

  8. mysql的sql分页函数limit使用 (转)

    http://www.cnblogs.com/beijingstruggle/p/5631603.html mysql的sql分页函数limit使用 My sql数据库最简单,是利用mysql的LIM ...

  9. Mysql分页之limit用法与limit优化

    Mysql limit分页语句用法 与Oracle和MS SqlServer相比,mysql的分页方法简单的让人想哭. --语法: SELECT * FROM table LIMIT [offset, ...

随机推荐

  1. Web安全知多少

    随着Web2.0.网络社交等一系列新型的互联网产品的诞生,基于Web环境的互联网应用越来越广泛,企业信息化的过程中,越来越多的应用都架设在Web平台上.Web业务的迅速发展吸引了黑客们的强烈关注,接踵 ...

  2. Caffe+Ubuntu14.04+CUDA7.5 环境搭建(新人向)指南

    序 本文针对想学习使用caffe框架的纯新手,如果文中有错误欢迎大家指出. 由于我在搭建这个环境的时候参考了许多网上的教程,但是没有截图,所以文中图片大多来源于网络. 本文没有安装matlab的步骤, ...

  3. python读取CSV文件

    python中有一个读写csv文件的包,直接import csv即可.利用这个python包可以很方便对csv文件进行操作,一些简单的用法如下. 1. 读文件 csv_reader = csv.rea ...

  4. SecureCRT - 使用方法和技巧

    1. 保活防掉线选项 -> 会话选项 -> 终端勾选 自动重新连接, 发送协议 NO-OP 每60秒 2. 拷贝与粘贴的设置选项 -> Global options -> Te ...

  5. SpringMVC集成shrio框架

    使用SHIRO的步骤:1,导入jar2,配置web.xml3,建立dbRelm4,在Spring中配置 添加所需jar包: <!--Apache Shiro所需的jar包--> <d ...

  6. 10个男孩和n个女孩共买了n2+8n+2本书,已知他们每人买的书本的数量是相同的,且女孩人数多于南海人数,问女孩人数是多少?(整除原理1.1.3)

    10个男孩和n个女孩共买了n2+8n+2本书,已知他们每人买的书本的数量是相同的,且女孩人数多于南海人数,问女孩人数是多少? 解: 因为,每个人买的书本的数量是相同的, 所以,10|n2+8n+2 所 ...

  7. 使用计算监控(Using computed observables)

    计算监控(Computed Observables) 如果有两个监控属性firstName, lastName,此时我们要显示full name,我们要怎么办呢? 这时,可以创建一个computed ...

  8. ssh连接ubuntu提示连接不上的问题

    今天在自己的电脑上安装了最新版本的 ubuntu (我都在root用户下运行,非root用户请添加sudo命令) uname -rvo 运行结果为 3.13.0-32-generic #57-Ubun ...

  9. php精度计算问题

    如果用php的+-*/计算浮点数的时候,可能会遇到一些计算结果错误的问题,比如echo intval( 0.58*100 );会打印57,而不是58,这个其实是计算机底层二进制无法精确表示浮点数的一个 ...

  10. Microsoft SqlSever 数据库--软谋1

    百度百科--Microsoft SqlSever SQL是英文Structured Query Language的缩写,意思为结构化查询语言.SQL语言的主要功能就是同各种数据库建立联系,进行沟通.按 ...