首页 > 代码库 > 【jsp 分页】mysql limit方式进行分页

【jsp 分页】mysql limit方式进行分页

项目结构示意图:

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(类似这样~)

 首页 上一页 下一页 尾页

商品编号商品名称商品价格
1bag68.8
2pen10.0
3pencil2.0
4mobile968.8
5bag68.8

【jsp 分页】mysql limit方式进行分页