Jsp的分页操作源代码

Jsp的分页操作源代码

一 分页操作的分析:

1.层的问题

Com.csdn.domaim

Com.csdn.dao

Com.csdn.daoImpl

Com.csdn.service 接口

Com.csdn.serviceImpl 实现类

Com.csdn.web 控制器

Com.csdn.web.filter

Com.csdn.web.listener

Com.csdn.util

2.如何实现的问题

StuentBean中定义了几个私有的属性: id name age address

StudentDao接口用于实现对数据库中属性的封装。

StudntService接口:定义方法,用数据库处理的方法

StudentServicImpl实现类

ControllerService:控制器:接收客户端的请求

List.jsp 显示所有的信息

3.分页显示:

首先先检查是否与数据库连接,可以先把所有的都输出。

然后要点击浏览器中的超链接来获取从数据库中读取的数据并显示,在超链接的时候要传参数,通过对servlet层的访问,在servlet层中对从数据库中的数据进行读取之后,通过判断再把参数传给浏览器并显示从数据库中调用的数据

二 代码的实现和说明

1.首先创建数据库,如图:

并从数据库中插入数据

2.在java中把数据库中的数据封装成类 StudentBean.java

publicclass StudentBean {

privateint id;

private String name;

privateint age;

private String address;

public StudentBean() {

super();

// TODO Auto-generated constructor stub

}

public StudentBean(int id, String name, int age, String address) {

super();

this.id = id;

this.name = name;

this.age = age;

this.address = address;

}

publicint getId() {

return id;

}

publicvoid setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

publicvoid setName(String name) {

this.name = name;

}

publicint getAge() {

return age;

}

publicvoid setAge(int age){

this.age = age;

}

public String getAddress() {

return address;

}

publicvoid setAddress(String address) {

this.address = address;

}

@Override

public String toString() {

return "StudentBean [address=" + address + ", age=" + age +", id="

+ id + ", name=" + name + "]";

}

}

3.创建实现对数据库数据的查找和分页的查找,首先先创建一个dao层,并在dao层写上一个接口和一个daoImpl两个java类,接口是为了在service层中与servetl成的连接,首先创建StudentDao.java

import java.util.List;

import com.hbsi.domain.StudentBean;

public interface StudentDao {

//返回所有记录行

public List<StudentBean> findAll();

//返回指定页中显示的记录行(一共有多少页,共多长)

public List<StudentBean> listPage(intcurrentPage,int pageSize);

//返回所有记录的行数

public int getSize();

}

再创建实现类 StudentDaoImpl.java

package com.hbsi.dao;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.LinkedList;

import java.util.List;

import com.hbsi.domain.StudentBean;

//接口的实现类

public class StudentDaoImpl implements StudentDao {

//声明操作的数据库对象

private static Connection conn;

private PreparedStatement pstmt;

private ResultSet rs;

//第一步:准备驱动程序,构造到项目路径中

private static final StringURL="jdbc:mysql://localhost:3306/demo?user=root&password=qiao&useUnicode=true&characterEncoding=utf8";

static{

try {

//第二步:加载驱动程序

Class.forName("com.mysql.jdbc.Driver");

//第三步:获取连接对象

conn = DriverManager.getConnection(URL);

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

private int size;//记录多少行

public List<StudentBean> findAll() {

//存放读取的数据

List<StudentBean> list = newLinkedList<StudentBean>();

try {

pstmt = conn.prepareStatement("select * fromstudent");

rs = pstmt.executeQuery();

//从结果集中读取

while(rs.next()){

StudentBean s = new StudentBean();

s.setId(rs.getInt(1));

s.setName(rs.getString(2));

s.setAge(rs.getInt(3));

s.setAddress(rs.getString(4));

list.add(s);

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

size=list.size();

return list;

}

//获取总的记录行数

public int getSize() {

// TODO Auto-generated method stub

findAll();

return size;

}

//截取的读取

public List<StudentBean> listPage(int currentPage,int pageSize) {

//存放读取的数据

List<StudentBean> list = newLinkedList<StudentBean>();

try {

//记录行

int recordIndex=(currentPage-1)*pageSize;

pstmt = conn.prepareStatement("select * from studentlimit ?,?");

int index =1;

pstmt.setInt(index++, recordIndex);

pstmt.setInt(index++, pageSize);

//从结果集中读

rs = pstmt.executeQuery();

while(rs.next()){

StudentBean s = new StudentBean();

s.setId(rs.getInt(1));

s.setName(rs.getString(2));

s.setAge(rs.getInt(3));

s.setAddress(rs.getString(4));

list.add(s);

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return list;

}

}

4.service层是业务层,是是和其他接口的层

首先创建StudentService.java

package com.hbsi.service;

import java.util.List;

import com.hbsi.domain.StudentBean;

public interface StudentService {

public List<StudentBean> findAll();

public List<StudentBean> listPage(intcurrentPage,int pageSzie);

//得到所有的记录行

public int getSize();

}

再创建StudentserviceImpl.java

package com.hbsi.service;

import java.util.List;

import com.hbsi.dao.StudentDaoImpl;

import com.hbsi.domain.StudentBean;

public class StudentServceImpl implements StudentService{

StudentDaoImpl dao = new StudentDaoImpl();

public List<StudentBean> findAll() {

// TODO Auto-generated method stub

return dao.findAll();

}

public List<StudentBean> listPage(int currentPage,int pageSize) {

// TODO Auto-generated method stub

return dao.listPage(currentPage, pageSize);

}

public int getSize() {

// TODO Auto-generated method stub

return dao.getSize();

}

}

5.jsp页面的实现 list.jsp

<%@ page language="java" import="java.util.*,com.hbsi.domain.*"

pageEncoding="utf-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme() + "://"

+ request.getServerName() + ":" +request.getServerPort()

+ path + "/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

<title>My JSP 'list.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet"type="text/css" href="styles.css">

-->

</head>

<body>

<!-- 读取集合中 的数据 -->

<%

List<StudentBean> list = (List<StudentBean>)request.getAttribute("list");

int pageNo = Integer.parseInt(request.getParameter("pageNo"));

%>

<h3>

学生信息表

</h3>

<!-- 读取-->

<table>

<%

for (int i = 0; i < list.size(); i++) {

%>

<tr>

<td><%=list.get(i).getId() %></td>

<td><%=list.get(i).getName() %></td>

<td><%=list.get(i).getAge()%></td>

<td><%=list.get(i).getAddress()%></td>

</tr>

<%

}

%>

</table><br/>

<a href="listStudent?pageNo=1">第一页</a> <a href="listStudent?pageNo=<%=pageNo-1 %>">上一页</a> <a href="listStudent?pageNo=<%=pageNo+1 %>">下一页</a> <a href="">最后页</a>

</body>

</html>

6.servlet层的实现 ControllerServlet.java

package com.hbsi.web;

import java.io.IOException;

import java.util.List;

importjavax.servlet.RequestDispatcher;

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

import com.hbsi.domain.StudentBean;

importcom.hbsi.service.StudentServceImpl;

public class ControllerServletextends HttpServlet {

/**

*

*/

private static final long serialVersionUID = 1L;

public ControllerServlet() {

super();

}

public void destroy() {

super.destroy(); // Just puts "destroy" stringin log

// Put your code here

}

public void doGet(HttpServletRequest request,HttpServletResponse response)

throws ServletException, IOException {

doPost(request, response);

}

public void doPost(HttpServletRequest request,HttpServletResponse response)

throws ServletException, IOException {

// 通过服务层得到数据

StudentServceImpl service = new StudentServceImpl();

// List<StudentBean> list = service.findAll();

// 分页的操作

// 计算一下一共有多少页

int total = service.getSize();// 一共有多少行记录

int pageSize = 3;// 每页显示的记录行数

int totalPages = total / pageSize;//共有多少个页面显示

totalPages = (total % pageSize == 0) ? totalPages :totalPages + 1;// 总共有total页

//显示的页数

int currentPage = 1;

if (request.getParameter("pageNo") != null) {

currentPage = Integer.parseInt(request.getParameter("pageNo"));

}

if (currentPage < 1) {

currentPage = 1;

}

if(currentPage>totalPages){

currentPage=totalPages;

}

List<StudentBean> list=service.listPage(currentPage, pageSize);

// servlt和jsp的桥梁,设置作用域的范围

request.setAttribute("list", list);

// 通过jsp页面显示所有的数据,请求的转向

RequestDispatcher rd =request.getRequestDispatcher("list.jsp?pageNo="+currentPage);

rd.forward(request, response);

}

public void init() throws ServletException {

// Put your code here

}

}

这样简单的分页就做好了,大家好好看看吧!!本人是jsp的初学者,希望多多指点!

 

/* * @(#)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; } }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值