mysql实现分页jsp javabean实现_java-web分页操作实现(javaBean+Servlet+jsp)

本文介绍了Java Web项目中使用MySQL数据库实现分页功能的方法,通过Servlet和JSP配合,详细讲解了分页概念、逻辑及代码实现,包括分页查询、总记录数和总页数的计算等。
摘要由CSDN通过智能技术生成

Java-web分页操作(jsp+servlet+javaBean)

一   分页操作分析

分页在web项目中是非常重要的技术,打开每一个网页都可以看到分页

1.疑问的出现

在写分页前要了解什么是分页,分页一共有多少个方法、多少个参数,应该如何编写方法的实现和定义参数的变量

2.疑问的解决

分页一般分为首页、上一页、下一页、末页,还要得到总记录数,总页数,下面来详细介绍一下它们的概念

如果设当前页为newPage

(1)当前页  ---------    打开网页时看到的页面

(2)首页  -----------   第一页          newPage=1

(3)上一页  ---------   当前页-1       newPage-1

(4)下一页  ---------   当前页+1      newPage+1

(5)末页    ---------   当前页==总页数  countPage=newPage

(6)总记录数 -------- select count(*) from 表名

(7)总页数  --------- 总记录数%每页显示的记录数=0 ? 总记录数/每页显示的记录数: 总记录数/每页显示的记录数+1

(8)显示当前页的分析    每页显示10条记录

第1页:newpage=1         起始记录为0      10

第2页:newpage=2         起始记录  10     10

第3页:newpage=3         起始记录  20     10

第4页:newpage=4         起始记录为30     10

第5页:newpage=5         起始记录  40     10

第6页:newpage=6         起始记录  50

第n页 newpage=n         (newpage-1)*pageSize

(9)查询指定的页面

第一页:Select id,name,address from test limit 0,10       注:从0开始查询,每页显示10条记录

第二页:Select id,name,address from test limit 20,10

第三页:Select id,name,address from test limit 30,10

第n页:Select id,name,address from test limit (newpage-1)*pageSize,pagesize

二  功能的实现

1.创建数据库(mysql)

useecho;DROP TABLE IF EXISTS`test`;CREATE TABLE`test` (

`id`int(11) NOT NULLAUTO_INCREMENT,

`name`varchar(50) NOT NULL,

`address`varchar(50) NOT NULL,PRIMARY KEY(`id`)

) ENGINE=InnoDB AUTO_INCREMENT=98 DEFAULT CHARSET=gbk;INSERT INTO `test` VALUES(1,'白雪公主','宫殿'),

(2,'小矮人','森林'),

(3,'萝卜','菜地'),

(4,'白菜','菜地'),

(5,'小猪','菜园'),

(6,'土豆','菜地'),

(7,'牛仔宝','牛栏'),

(8,'玉米','菜地'),

(9,'兔子','菜地'),

(10,'刀豆','菜地'),

(11,'青菜','菜地');

2.创建功能模块

eb2b5d6ee54710166c9911689e37a718.png

Paging.jsp

package com.csdn.paging.domain;

public class Paging {

private Integer id;

private String name;

private String address;

public Paging() {

super();

}

public Paging(Integer id, String name, String address) {

super();

this.id = id;

this.name = name;

this.address = address;

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

@Override

public String toString() {

return "Paging [id=" + id + ", name=" + name + ", address=" + address

+ "]";

}

}

PagingDao.java

packagecom.csdn.paging.dao;importjava.util.List;importcom.csdn.paging.domain.Paging;public interfacePagingDao {//显示总的记录条数

Integer getCountRecord();//根据当前页到结束页的查询

ListfindIimitPage(Integer newPage);//总的页数

Integer getCountPage();

}

PagingDaoImpl.java

packagecom.csdn.paging.dao;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.ArrayList;importjava.util.List;importcom.csdn.paging.domain.Paging;public class PagingDaoImpl implementsPagingDao {private static final Integer pageSize = 10;//每页显示5条数据

private Integer countRecord;//共有多少条记录

private Integer countPage;//共有多少页//private static final String URL = "jdbc:MySQL://localhost:3306/echo?user=root&password=123456&useUnicode=true&characterEncoding=utf-8";

private staticConnection conn;privatePreparedStatement pstmt;privateResultSet rs;static{try{//加载驱动

Class.forName("com.mysql.jdbc.Driver");//建立连接//conn = DriverManager.getConnection(URL);//定义数据库地址url,并设置编码格式

conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/echo?useUnicode=true&characterEncoding=utf-8&useSSL=false", "root", "123456");

}catch(ClassNotFoundException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(SQLException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}publicInteger getCountRecord() {//设置返回值

Integer count = 0;//获取连接//定义sql语句 查询出记录条数

String sql = "select count(*) as con from test";try{//创建预处理对象

pstmt =conn.prepareStatement(sql);//为占位符赋值//执行更新语句

rs =pstmt.executeQuery();//判断

if(rs.next()) {

count= rs.getInt("con");

}//计算出总页数,并从getCountPage方法中获取

this.countPage = ((count % pageSize) != 0 ? (count / pageSize + 1): (count /pageSize));//释放资源

if (rs != null) {

rs.close();

}if (pstmt != null) {

pstmt.close();

}

}catch(SQLException e) {//TODO Auto-generated catch block

e.printStackTrace();

}returncount;

}//得到总的页数

publicInteger getCountPage() {//TODO Auto-generated method stub

returncountPage;

}//根据传过来的数值条件查询

public ListfindIimitPage(Integer newPage) {//修改返回值

List entities = new ArrayList();//获取连接//定义SQL语句

String sql = "select id,name,address from test limit ?,?";//参数为(newPage - 1) * pageSize和pageSize

try{//创建预处理对象

pstmt =conn.prepareStatement(sql);//为占位符赋值

int index = 1;

pstmt.setObject(index++, (newPage - 1) *pageSize);

pstmt.setObject(index++, pageSize);//执行更新

rs =pstmt.executeQuery();//判断

while(rs.next()) {

Paging entity= newPaging();

entity.setId(rs.getInt("id"));

entity.setName(rs.getString("name"));

entity.setAddress(rs.getString("address"));

entities.add(entity);

}//释放资源

if (rs != null) {

rs.close();

}if (pstmt != null) {

pstmt.close();

}

}catch(SQLException e) {//TODO Auto-generated catch block

e.printStackTrace();

}returnentities;

}

}

PagingServlet.java

注:dopost doget都是父类HttpServlet里的方法 不要直接copy,先生成方法再copy代码。我就是出现显示不出来数据的错误,原因就是servlet没有接收jsp的请求,方法没有生效。

packagecom.csdn.servlet;importjava.io.IOException;importjava.util.ArrayList;importjava.util.List;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importcom.csdn.paging.dao.PagingDaoImpl;importcom.csdn.paging.domain.Paging;public class PagingServlet extendsHttpServlet {

@Overrideprotected voiddoGet(HttpServletRequest req, HttpServletResponse resp)throwsServletException, IOException {//TODO Auto-generated method stub

System.out.println("doget");this.doPost(req, resp);

}

@Overrideprotected voiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {//TODO Auto-generated method stub

System.out.println("dopost");

request.setCharacterEncoding("utf-8");

response.setContentType("text/html;charset=utf-8");

String npage= request.getParameter("newPage");

System.out.println("npage="+npage);

PagingDaoImpl pageService=newPagingDaoImpl();

List entities = pageService.findIimitPage(newInteger(npage));int countRecord =pageService.getCountRecord();int countPage =pageService.getCountPage();

request.setAttribute("entities", entities);

request.setAttribute("countPage", countPage);

request.setAttribute("newPage", npage);

request.setAttribute("countRecord", countRecord);

request.getRequestDispatcher("/paging.jsp").forward(request, response);

}

}

paging.jsp

注:一定要在web-inf的lib下添加jar包jstl.jar、standard.jar.否则该行会报错。

安装JSTL 库步骤如下:

下载jakarta-taglibs-standard-1.1.2.zip 包并解压,将jakarta-taglibs-standard-1.1.2/lib/下的两个jar文件:standard.jar和jstl.jar文件拷贝到/WEB-INF/lib/下。

Stringpath=request.getContextPath();StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>

">

paging.jsp

查看所有信息

${entity.id}${entity.name}${entity.address}

首页

上一页

=countPage?countPage:newPage+1}">下一页

末页

web.xml

Login.html

Login.htm

paging.jsp

PagingServlet

com.csdn.servlet.PagingServlet

PagingServlet

/servlet/PagingServlet

效果图如下:

820a2f21ba764881da86456d8c2a550f.png

/* * @(#)PageControl.java 1.00 2004-9-22 * * Copyright 2004 2004 . All rights reserved. * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.hexiang.utils; /** * PageControl, 分页控制, 可以判断总页数和是否有上下页. * * 2008-07-22 加入输出上下分页HTML代码功能 * * @author HX * @version 1.1 2008-9-22 */ public class PageBean { /** 每页显示记录数 */ private int pageCount; /** 是否有上一页 */ private boolean hasPrevPage; /** 记录总数 */ private int recordCount; /** 是否有下一页 */ private boolean hasNextPage; /**总页面数 */ private int totalPage; /** 当前页码数 */ private int currentPage; /** * 分页前的页面地址 */ private String pageUrl; /** * 输出分页 HTML 页面跳转代码, 分链接和静态文字两种. * 2008-07-22 * @return HTML 代码 */ public String getPageJumpLinkHtml() { if(StringUtil.isEmpty(pageUrl)) { return ""; } // 检查是否有参数符号, 没有就加上一个? if(pageUrl.indexOf('?') == -1) { pageUrl = pageUrl + '?'; } StringBuffer buff = new StringBuffer("<span id='pageText'>"); // 上一页翻页标记 if(currentPage > 1) { buff.append("[ <a href='" + pageUrl + "&page=" + (currentPage - 1) + "' title='转到第 " + (currentPage - 1) + " 页'>上一页</a> ] "); } else { buff.append("[ 上一页 ] "); } // 下一页翻页标记 if(currentPage < getTotalPage()) { buff.append("[ <a href='" + pageUrl + "&page=" + (currentPage + 1)+ "' title='转到第 " + (currentPage + 1) + " 页'>下一页</a> ] "); } else { buff.append("[ 下一页 ] "); } buff.append("</span>"); return buff.toString(); } /** * 输出页码信息: 第${currentPage}页/共${totalPage}页 * @return */ public String getPageCountHtml() { return "第" + currentPage + "页/共" + getTotalPage() + "页"; } /** * 输出 JavaScript 跳转函数代码 * @return */ public String getJavaScriptJumpCode() { if(StringUtil.isEmpty(pageUrl)) { return ""; } // 检查是否有参数符号, 没有就加上一个? if(pageUrl.indexOf("?") == -1) { pageUrl = pageUrl + '?'; } return "<script>" + "// 页面跳转函数\n" + "// 参数: 包含页码的表单元素,例如输入框,下拉框等\n" + "function jumpPage(input) {\n" + " // 页码相同就不做跳转\n" + " if(input.value == " + currentPage + ") {" + " return;\n" + " }" + " var newUrl = '" + pageUrl + "&page=' + input.value;\n" + " document.location = newUrl;\n" + " }\n" + " </script>"; } /** * 输出页面跳转的选择框和输入框. 示例输出: * <pre> 转到 <!-- 输出 HTML SELECT 元素, 并选当前页面编码 --> <select onchange='jumpPage(this);'> <c:forEach var="i" begin="1" end="${totalPage}"> <option value="${i}" <c:if test="${currentPage == i}"> selected </c:if> >第${i}页</option> </c:forEach> </select> 输入页码:<input type="text" value="${currentPage}" id="jumpPageBox" size="3"> <input type="button" value="跳转" onclick="jumpPage(document.getElementById('jumpPageBox'))"> </pre> * @return */ public String getPageFormJumpHtml() { String s = "转到\n" + "\t <!-- 输出 HTML SELECT 元素, 并选当前页面编码 -->\n" + " <select onchange='jumpPage(this);'>\n" + " \n"; for(int i = 1; i <= getTotalPage(); i++ ) { s += "<option value=" + i + "\n"; if(currentPage == i) { s+= " selected "; } s += "\t>第" + i + "页</option>\n"; } s+= " </select>\n" + " 输入页码:<input type=\"text\" value=\"" + currentPage + "\" id=\"jumpPageBox\" size=\"3\"> \n" + " <input type=\"button\" value=\"跳转\" onclick=\"jumpPage(document.getElementById('jumpPageBox'))\"> "; return s; } /** * 进行分页计算. */ private void calculate() { if (getPageCount() == 0) { setPageCount(1); } totalPage = (int) Math.ceil(1.0 * getRecordCount() / getPageCount()); // 总页面数 if (totalPage == 0) totalPage = 1; // Check current page range, 2006-08-03 if(currentPage > totalPage) { currentPage = totalPage; } // System.out.println("currentPage=" + currentPage); // System.out.println("maxPage=" + maxPage); // // Fixed logic error at 2004-09-25 hasNextPage = currentPage < totalPage; hasPrevPage = currentPage > 1; return; } /** * @return Returns the 最大页面数. */ public int getTotalPage() { calculate(); return totalPage; } /** * @param currentPage * The 最大页面数 to set. */ @SuppressWarnings("unused") private void setTotalPage(int maxPage) { this.totalPage = maxPage; } /** * 是否有上一页数据 */ public boolean hasPrevPage() { calculate(); return hasPrevPage; } /** * 是否有下一页数据 */ public boolean hasNextPage() { calculate(); return hasNextPage; } // Test public static void main(String[] args) { PageBean pc = new PageBean(); pc.setCurrentPage(2); pc.setPageCount(4); pc.setRecordCount(5); pc.setPageUrl("product/list.do"); System.out.println("当前页 " + pc.getCurrentPage()); System.out.println("有上一页 " + pc.hasPrevPage()); System.out.println("有下一页 " + pc.hasNextPage()); System.out.println("总页面数 " + pc.getTotalPage()); System.out.println("分页 HTML 代码 " + pc.getPageJumpLinkHtml()); } /** * @return Returns the 当前页码数. */ public int getCurrentPage() { return currentPage; } /** * 设置当前页码, 从 1 开始. * @param currentPage * The 当前页码数 to set. */ public void setCurrentPage(int currentPage) { if (currentPage <= 0) { currentPage = 1; } this.currentPage = currentPage; } /** * @return Returns the recordCount. */ public int getRecordCount() { return recordCount; } /** * @param recordCount * The recordCount to set. */ public void setRecordCount(int property1) { this.recordCount = property1; } /** * @return Returns the 每页显示记录数. */ public int getPageCount() { return pageCount; } /** * @param pageCount * The 每页显示记录数 to set. */ public void setPageCount(int pageCount) { this.pageCount = pageCount; } public String getPageUrl() { return pageUrl; } public void setPageUrl(String value) { pageUrl = value; } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值