很好的分页实例代码(JSP)

 
1:首先创建数据库链接类,我的博客前面有源码
2:创建封装你要分页的那个数据库表的Bean
3:封装实现分页功能的功能Bean 具体代码见下:
 

import java.util.ArrayList;
import java.sql.*;

public class PageBean {

    private int curPage = 1; //当前是第几页
    private int maxPage; //一共有多少页
    private int maxRowCount; //一共有多少行
    public int rowsPerPage = 10; //每页多少行

    Connection conn;
    public ArrayList data;

    public PageBean() throws Exception {
        this.setPageBean();
    }
    public int getCurPage() {
        return curPage;
    }

    public int getMaxPage() {
        return maxPage;
    }

    public int getMaxRowCount() {
        return maxRowCount;
    }

    public int getRowsPerPage() {
        return rowsPerPage;
    }

    public void setCurPage(int curPage) {
        this.curPage = curPage;
    }

    public void setMaxPage(int maxPage) {
        this.maxPage = maxPage;
    }

    public void setMaxRowCount(int maxRowCount) {
        this.maxRowCount = maxRowCount;
    }

    public void setRowsPerPage(int rowsPerPage) {
        this.rowsPerPage = rowsPerPage;
    }

    //得到要显示于本页的数据
    public PageBean getResult(String page) throws Exception {
        try {
            PageBean pageBean = new PageBean();
            ArrayList list = new ArrayList();
            int pageNum = Integer.parseInt(page);
            Statement stmt = conn.createStatement();
            String strSql = "select top " + pageNum * pageBean.rowsPerPage +
                            " * from employee";//改成你的表
            ResultSet rset = stmt.executeQuery(strSql);
            int i = 0;
            while (rset.next()) {

                    //这里要和表的字段对应起来!!!!
                    Employee item=new Employee();
                    item.setEmp_id(rset.getString("emp_id"));
                    item.setFname(rset.getString("fname"));
                    item.setMinit(rset.getString("minit"));
                    item.setLname(rset.getString("lname"));
                    item.setJob_id(rset.getInt("job_id"));
                    item.setJob_lvl(rset.getInt("job_lvl"));
                    item.setPub_id(rset.getString("pub_id"));
                    item.setHire_date(rset.getString("hire_date"));
                    list.add(item);

                i++;
            }
            ConnectionManager.closeResultSet(rset);
            ConnectionManager.closeStatement(stmt);
            pageBean.setCurPage(pageNum);
            pageBean.data = list;
            return pageBean;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;

        }
    }
    //获取总行数
    public int getAvailableCount() throws Exception {
        int ret = 0;
        conn = ConnectionManager.getConnection();
        Statement stmt = conn.createStatement();
        String strSql = "select * from employee";//改成你的表
        ResultSet rset = stmt.executeQuery(strSql);
        while (rset.next()) {
            ret++;
        }
        return ret;
    }
    //初始化时对PageBean进行设置
    public void setPageBean() throws Exception {

        //得到总行数
        this.setMaxRowCount(this.getAvailableCount());

        if (this.maxRowCount % this.rowsPerPage == 0) { //根据总行数计算总页数
            this.maxPage = this.maxRowCount / this.rowsPerPage;
        } else {
            this.maxPage = this.maxRowCount / this.rowsPerPage + 1;
        }
    }

}

 

4:建立中间中转的Servlet  PageServlet: 代码如下:

public void init() throws ServletException {
  }

  //Process the HTTP Get request
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws
      ServletException, IOException {
    try
      {
            PageBean page1=new PageBean();
            PageBean page2=page1.getResult((String)request.getParameter("jumpPage"));

              //把PageBean保存到request对象中。注意:viewpage.jsp里jsp:useBean id必须为才可以"page2"!!!
              request.setAttribute("page2",page2);
      }
      catch(Exception e)
      {
              e.printStackTrace();
      }

          /**
       *把视图派发到viewForum.jsp
       */
      javax.servlet.RequestDispatcher dis=request.getRequestDispatcher("viewpage.jsp");
      dis.forward(request,response);

 }

5:现在建立现实JSP页面 viewpage.jsp:

<%@ page contentType="text/html; charset=GBK" import="java.util.*,pagetest.Employee" %>
<jsp:useBean id="page2" scope="request" class="pagetest.PageBean"/>
<script language="JavaScript" type="text/JavaScript">
function Jumping(){
  document.PageForm.submit();
  return ;
}

function gotoPage(pagenum){
  document.PageForm.jumpPage.value = pagenum;
  document.PageForm.submit();
  return ;
}
</script>
<html>
<head>
<title>
分页功能
</title>
</head>
<body bgcolor="#ffffff">
<table border="1">
<%
String s=String.valueOf(page2.getCurPage());
try{
ArrayList list=page2.getResult(s).data;
for(int i=0;i<list.size();i++){
  Employee emp=(Employee)list.get(i);
%>
<tr>
<td><%=emp.getEmp_id()%></td>
<td><%=emp.getFname()%></td>
<td><%=emp.getHire_date()%></td>
<td><%=emp.getJob_id()%></td>
<td><%=emp.getJob_lvl()%></td>
<td><%=emp.getLname()%></td>
<td><%=emp.getMinit()%></td>
<td><%=emp.getPub_id()%></td>
</tr>
<%
 }
}catch(Exception e){}
%>
</table>
<%if(page2.getMaxPage()!=1){ %>
<form name="PageForm" action="pageservlet" method="post">
每页
<%=page2.rowsPerPage%>


<%=page2.getMaxRowCount()%>


<%=page2.getCurPage()%>


<%=page2.getMaxPage()%>
<BR>
<%
  if (page2.getCurPage() == 1) {
    out.print(" 首页 上一页");
  }
  else {
%>
<a HREF="javascript:gotoPage(1)">首页</A>
<a HREF="javascript:gotoPage(<%=page2.getCurPage()-1%>)">上一页</A>
<%}%>
<%
  if (page2.getCurPage() == page2.getMaxPage()) {
    out.print("下一页 尾页");
  }
  else {
%>
<a HREF="javascript:gotoPage(<%=page2.getCurPage()+1%>)">下一页</A>
<a HREF="javascript:gotoPage(<%=page2.getMaxPage()%>)">尾页</A>
<%}%>
转到第
<SELECT name="jumpPage" onchange="Jumping()">
<%
  for (int i = 1; i <= page2.getMaxPage(); i++) {
    if (i == page2.getCurPage()) {
%>
  <OPTION selected value="<%=i%>"><%=i%> </OPTION>
<%} else {%>
  <OPTION value="<%=i%>"><%=i%> </OPTION>
<%}
  }%>
</SELECT>

</form>
<%}%>
</body>
</html>

 

现在运行 就可以看到效果

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
自己收集的jsp分页代码。对于北大青鸟Y2的学员可能有用吧。自己也在做这个项目。这里有增、删、该、查加分页。有上一页、下一页、首页、尾页、第几页、还有带数字和点的分页。可以说是非常好的分页代码。想要的朋友自己处下载 <%@ page contentType="text/html; charset=GB2312" language="java" import="java.sql.*" errorPage="" %> <%@ page import="java.io.*" %> <%@ page import="java.util.*" %> <% java.sql.Connection sqlCon; //数据库连接对象 java.sql.Statement sqlStmt; //SQL语句对象 ResultSet sqlRst=null; //java.sql.ResultSet sqlRst; //结果集对象 java.lang.String strCon; //数据库连接字符串 java.lang.String strSQL; //SQL语句 int intPageSize; //一页显示的记录数 int intRowCount; //记录总数 int intPageCount; //总页数 int intPage; //待显示页码 java.lang.String strPage; int i; //设置一页显示的记录数 intPageSize = 2; //取得待显示页码 strPage = request.getParameter("page"); if(strPage==null){ //表明在QueryString中没有page这一个参数,此时显示第一页数据 intPage = 1; } else{ //将字符串转换成整型 intPage = java.lang.Integer.parseInt(strPage); if(intPage<1) intPage = 1; } %><% String DBUser="sa"; String DBPassword="88029712"; //String DBServer="127.0.0.1"zjprice; String DBUrl="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs"; //创建语句对象 //Class.forName("org.gjt.mm.mysql.Driver").newInstance(); Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance(); sqlCon=java.sql.DriverManager.getConnection(DBUrl,DBUser,DBPassword); sqlStmt=sqlCon.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY); //执行SQL语句并获取结果集 String sql=null; String search=""; String ToPage=request.getParameter("ToPage"); if(request.getParameter("search")!=null &&!request.getParameter("search").equals("")) {search=new String(request.getParameter("search").trim().getBytes("8859_1")); } sql="select top 50 au_id,au_lname from authors "; /*sql="select*from ta,tb where id like'%"+search+"%'"; sql=sql+"or title like'%"+search+"%'"; sql=sql+"or time like'%"+search+"%'"; sql=sql+"or con like'%"+search+"%'"; sql=sql+"order by id";*/ sqlRst=sqlStmt.executeQuery(sql); //获取记录总数 sqlRst.last(); intRowCount = sqlRst.getRow(); //记算总页数 intPageCount = (intRowCount+intPageSize-1) / intPageSize; //调整待显示的页码 if(intPage>intPageCount) intPage = intPageCount; %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>test</title> </head> <body> <table border="1" cellspacing="0" cellpadding="0"> <tr> <th>标题id</th> <th>内容表</th> </tr> <% if(intPageCount>0) { //将记录指针定位到待显示页的第一条记录上 sqlRst.absolute((intPage-1) * intPageSize + 1); //显示数据 i = 0; while(i<intPageSize && !sqlRst.isAfterLast()){ %> <tr> <td> <%=sqlRst.getString(1)%> </td> <td> <%=sqlRst.getString(2)%> </td> </tr> <% sqlRst.next(); i++; } } %> <tr><td colspan="8">共有<font color=red><%= intRowCount %></font>条记录 当前<font color=red><%=intPage%>/<%=intPageCount%></font>页  <% if(intPageCount > 1){ %> <% if(intPage !=0){%> <a href="mysqlpage.jsp">首页</a> <%}if(intPage != 1){%><a href="mysqlpage.jsp?page=<%= intPage - 1 %>">上一页</a> <%}if(intPage<intPageCount){%><a href="mysqlpage.jsp?page=<%=intPage+1%>">下一页</a><%}%> <a href="mysqlpage.jsp?page=<%= intPageCount %>">尾页</a> <% } %>跳转到 <select name="page" onChange="javascript:this.form.submit();"> <% for(i=1;i<=intPageCount;i++){%> <option value="<%= i %>" <% if(intPage == i){%>selected<% } %>><%= i %></option> <% } %> </select>页 <%int m,n,p; %> <%if (intPage>1){ if(intPage-2>0){ m=intPage-2;} else { m=1;} if(intPage+2<intPageCount){ n=intPage+2;} else{ n=intPageCount; }%> 转到页码: [ <% for(p=m;p<=n;p++) { if (intPage==p){ %> <font color="black"><%=p %></font> <% } else{%> <a href=?page=<%=p %>><font color=red>[<%=p %>]</font></a> <% } }%>]<%} %> </td></tr> </table> </body> </html> <% //关闭结果集 sqlRst.close(); //关闭SQL语句对象 sqlStmt.close(); //关闭数据库 sqlCon.close(); %>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值