JSTL分页显示数据代码
- 格式:doc
- 大小:48.50 KB
- 文档页数:3
ShowRecordByPage.javapackage database.operation;import java.sql.*;import com.sun.rowset.*;public class ShowRecordByPage{ int pageSize=10; //每页显示的记录数int pageAllCount=0; //分页后的总页数int showPage=1 ; //当前显示页StringBuffer presentPageResult; //显示当前页内容CachedRowSetImpl rowSet; //用于存储ResultSet对象String databaseName="user"; //数据库名称String tableName="user_tab"; //表的名字String user="sa" ; //用户String password="123" ; //密码String 字段[]=new String[100] ;int 字段个数=0;public ShowRecordByPage(){ presentPageResult=new StringBuffer();try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newIns tance();}catch(Exception e){}}public void setPageSize(int size){ pageSize=size;字段个数=0;Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName;try{ Connectioncon=DriverManager.getConnection(uri,user,password);DatabaseMetaData metadata=con.getMetaData();ResultSet rs1=metadata.getColumns(null,null,tableName,null);int k=0;while(rs1.next()){ 字段个数++;字段[k]=rs1.getString(4); //获取字段的名字k++;}Statementsql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);ResultSet rs=sql.executeQuery("SELECT * FROM"+tableName);rowSet=new CachedRowSetImpl(); //创建行集对象rowSet.populate(rs);con.close(); //关闭连接st();int m=rowSet.getRow(); //总行数int n=pageSize;pageAllCount=((m%n)==0)?(m/n):(m/n+1);}catch(Exception exp){}}public int getPageSize(){ return pageSize;}public int getPageAllCount(){ return pageAllCount;}public void setShowPage(int n){ showPage=n;}public int getShowPage(){ return showPage;}public StringBuffer getPresentPageResult(){ if(showPage>pageAllCount)showPage=1;if(showPage<=0)showPage=pageAllCount;presentPageResult=show(showPage);return presentPageResult;}public StringBuffer show(int page){ StringBuffer str=new StringBuffer();str.append("<table border=1>");str.append("<tr>");for(int i=0;i<字段个数;i++){ str.append("<th>"+字段[i]+"</th>");}str.append("</tr>");try{ rowSet.absolute((page-1)*pageSize+1);for(int i=1;i<=pageSize;i++){ str.append("<tr>");for(int k=1;k<=字段个数;k++){ str.append("<td>"+rowSet.getString(k)+"</td>");}str.append("</tr>");rowSet.next();}}catch(SQLException exp){}str.append("</table>");return str;}public void setDatabaseName(String s){ databaseName=s.trim();}public String getDatabaseName(){ return databaseName;}public void setTableName(String s){ tableName=s.trim();}public String getTableName(){ return tableName;}public void setPassword(String s){ password=s.trim();;}public void setUser(String s){ user=s.trim();}public String getUser(){ return user;}}showByPage.jsp<%@ page contentType="text/html;charset=GB2312" %><%@ page import="java.sql.*" %><%@ page import="database.operation.*" %><jsp:useBean id="look" class="database.operation.ShowRecordByPage" scope="session" /><jsp:setProperty name="look" property="databaseName" value="factory" /><jsp:setProperty name="look" property="tableName" value="employee" /> <jsp:setProperty name="look" property="user" value="sa" /><jsp:setProperty name="look" property="password" value="sa" /><jsp:setProperty name="look" property="pageSize" value="2" /><HTML><BODY>数据库<jsp:getProperty name= "look" property="databaseName"/>中<jsp:getProperty name= "look" property="tableName"/>表的记录将被分页显示。
jsp分页,分页形式(1,2,3······)jsp中实现如下形式的分页(<1,2,3>)所需参数: 1.数据库或接⼝返回的数据的总条数(total)。
2.每页显⽰的条数。
(我将每页显⽰的条数定为了15条)⽤数据的总条数除以每页显⽰的条数,就是所要展⽰页数。
代码摘要如下: 后台:Integer total = (Integer) returnMap.get("total") ;/**//获取接⼝或数据库返回的数据总条数。
*/Integer totalpages = total%15==0?(total/15):(total/15)+1;//求总页数,这⼉我⽤的是三⽬运算,即:如果总数除以每页条数,没有余数,就返回得到的商,若有余数,则再给商加⼀。
这样就得到了⽐较全的页数。
request.setAttribute("totalpages", totalpages);//返回到前台 前端:(我是⽤jsp实现的)1.先获取返回值,再将返回值转化成int类型,便于做循环操作<%String path = request.getContextPath();String pageCount = request.getAttribute("totalpages").toString();int pagetotal = Integer.parseInt(pageCount);%><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>2.进⾏循环展⽰<% for (int i = 1; i <= pagetotal; i++) {%><a href="#" onclick="testPage();" value="<%=i%>" id="pages" class="number"><%=i%></a><%} %>在js中定义testPage();函数,将获取到的页数传到后台从⽽实现导航效果。
JSP 分页查询关键代码1.连接数据库的基类:package mons;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;public class GetConnection {protected Connection conn = null;//连接字符串protected PreparedStatement ps = null;//预编译并存储 SQL 指令protected ResultSet rs = null;//查询结果集private static final String DRIVER ="com.microsoft.sqlserver.jdbc.SQLServerDriver";//加载数据库驱动的字符串private static final String URL ="jdbc:sqlserver://localhost:1433;databaseName=BOOKDB";//连接数据库的字符串private static final String USERNAME = "sa";//数据库用户名private static final String PASSWORD = "accp";//数据库用户密码/***获得数据库连接*@return*/public Connection getConn() {Connection conn = null;try {Class.forName(DRIVER);//加载数据库驱动conn =DriverManager.getConnection(URL,USERNAME,PASSWORD);//连接数据库} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return conn;}/** 释放资源*/public void closeAll(){try {if(rs != null){rs.close();}if(ps != null){ps.close();}if(conn != null){conn.close();}} catch (SQLException e) {e.printStackTrace();}finally{conn = null;ps = null;rs = null;}}}2.实体类代码:package com.book.entity;public class Book {private int book_id;private String book_name;private String book_num;private String book_author;private double book_price;private String book_synopsis;private String book_publishTime;public String getBook_author() {return book_author;}public void setBook_author(String book_author) { this.book_author = book_author;}public int getBook_id() {return book_id;}public void setBook_id(int book_id) {this.book_id = book_id;}public String getBook_name() {return book_name;}public void setBook_name(String book_name) { this.book_name = book_name;}public String getBook_num() {return book_num;}public void setBook_num(String book_num) { this.book_num = book_num;}public double getBook_price() {return book_price;}public void setBook_price(double book_price) { this.book_price = book_price;}public String getBook_publishTime() {return book_publishTime;}public void setBook_publishTime(String book_publishTime) { this.book_publishTime = book_publishTime;}public String getBook_synopsis() {return book_synopsis;}public void setBook_synopsis(String book_synopsis) { this.book_synopsis = book_synopsis;}}3.分页查询代码:package com.book.pagin;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import mons.GetConnection;import com.book.entity.Book;public class BookPaginQuery extends GetConnection { private final int PAGEROW = 8;//每页显示的行数private int countRow;//总行数private int countPage;//总页数private int currentlyPage;//当前第几页/***得到总页数*@return*/public int getCountPage() {return countPage;}/***设置总页数*@param countPage*/public void setCountPage() {//通过总行数设置总页数if (this.countRow % this.PAGEROW == 0) {//如果总行数除以每页显示的行数余数为零时,总页数等于它们的商this.countPage = this.countRow / this.PAGEROW;} else {//否则,总页数等于它们的商加1this.countPage = this.countRow / this.PAGEROW + 1;}}/***得到总行数*@return*/public int getCountRow() {return countRow;}/***设置总行数*@param countRow*/public void setCountRow() {//通过聚合函数查询 TBL_BOOK 表中一共有多少条数据,并把值存储到 countRow 中String sql = "SELECT COUNT(*) FROM TBL_BOOK";try {PreparedStatement ps =super.getConn().prepareStatement(sql);ResultSet rs = ps.executeQuery();if (rs.next()) {this.countRow = rs.getInt(1);}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/***得到当前页数*@return*/public int getCurrentlyPage() {return currentlyPage;}/***设置当前页数*@param currentlyPage*/public void setCurrentlyPage(int currentlyPage) {this.currentlyPage = currentlyPage;}/***分页查询*@param page当前页数*@return*/public List<Book> myBookPaginQuery(int page){List<Book> bookList = new ArrayList<Book>();int num = (page-1) * this.PAGEROW; //要被排除的行数String sql = "SELECT top("+this.PAGEROW+") * FROM TBL_BOOK WHERE book_id NOT IN (SELECT TOP("+num+") book_id FROM TBL_BOOK)";try {PreparedStatement ps =super.getConn().prepareStatement(sql);//预编译 SQL 指令并把预编译好的 SQL 存储在 PreparedStatement 对象中ResultSet rs = ps.executeQuery(); //执行预编译好的 SQL 指令,并把获得的查询结果集存储在 ResultSet 对象中while(rs.next()) {//通过 while 循环迭代出结果集中的所有数据,并把它们存储在 List<Book> 集合中Book book = new Book();book.setBook_id(rs.getInt("book_id"));book.setBook_name(rs.getString("book_name"));book.setBook_num(rs.getString("book_num"));book.setBook_author(rs.getString("book_author"));book.setBook_price(rs.getDouble("book_price"));book.setBook_synopsis(rs.getString("book_synopsis"));book.setBook_publishTime(rs.getString("book_publishTime"));bookList.add(book);}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return bookList;}}4.JSP 页面代码:<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <jsp:directive.page import="com.book.pagin.BookPaginQuery"/><jsp:directive.page import="com.book.entity.Book"/><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>图书信息</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><%request.setCharacterEncoding("UTF-8"); //设置编码集String strPageNum = request.getParameter("pageNum"); //获得当前页数的字符串int pageNum = 1;//把当前页数的字符串转化为数字,如果转化失败,则设置当前页数为 1 ,即首页try{pageNum = Integer.parseInt(strPageNum);} catch (Exception e){pageNum = 1;}BookPaginQuery bookPaginQuery = new BookPaginQuery();//实例化BookPaginQuery 类,得到 bookPaginQuery 对象bookPaginQuery.setCountRow(); //设置总行数bookPaginQuery.setCountPage(); //设置总页数int countPage = bookPaginQuery.getCountPage(); //获得总页数//如果当前页数小于 0 或大于总页数,则把当前页重新设为 1 ,即首页if (pageNum<=0 || pageNum>countPage){pageNum = 1;}bookPaginQuery.setCurrentlyPage(pageNum); //设置当前页int currentlyPage = bookPaginQuery.getCurrentlyPage(); //获得当前页List<Book> bookList = bookPaginQuery.myBookPaginQuery(pageNum); //分页查询if(bookList!=null && bookList.size()>0) {%><table border="1" align="center"><tr><th align="center">图书名称</th><th align="center">图书编号</th><th align="center">作者</th><th align="center">价格</th><th align="center">图书简介</th><th align="center">出版日期</th></tr><%for (int i=0; i<bookList.size(); i++) {Book book = bookList.get(i);%><tr><td width="200"><%=book.getBook_name() %></td><td width="100"><%=book.getBook_num() %></td><td width="50"><%=book.getBook_author() %></td><td width="50"><%=book.getBook_price() %></td><td width="300"><%=book.getBook_synopsis() %></td><tdwidth="100"><%=book.getBook_publishTime().substring(0,10) %></td> </tr>}%><tr><td colspan="6" align="center"><%if(currentlyPage==1){%>共<%=countPage %>页 当前第<%=currentlyPage %>页 首页 上一页 <a href="index.jsp?pageNum=<%=currentlyPage+1 %>">下一页</a> <a href="index.jsp?pageNum=<%=countPage %>">尾页</a> <%}else if(currentlyPage==countPage){%>共<%=countPage %>页 当前第<%=currentlyPage %>页 <a href="index.jsp?pageNum=1">首页</a> <a href="index.jsp?pageNum=<%=currentlyPage-1 %>">上一页</a> 下一页 尾页 <%}else{%>共<%=countPage %>页 当前第<%=currentlyPage %>页 <a href="index.jsp?pageNum=1">首页</a> <a href="index.jsp?pageNum=<%=currentlyPage-1 %>">上一页</a> <a href="index.jsp?pageNum=<%=currentlyPage+1 %>">下一页</a> <a href="index.jsp?pageNum=<%=countPage %>">尾页</a> <%}%></td></tr></table>}else{%><h2 align="center">对不起,没有相应的信息……</h2> <%}%></body></html>最后效果如下图:点击首页:点击下一页:点击尾页:。
jsp分页显⽰的实现代码最近这⼏天在做JSP留⾔板设计的过程中,遇到了⼀个问题。
先看⼀张截图:这是随便在⼀个新闻的留⾔页⾯截的图,假如留⾔条数太多,那整个页⾯得排好长好长,这就直接给⽤户造成了⿇烦、不舒服的感受,所以,解决这个问题,通常采⽤分页显⽰的⽅法。
要把页⾯显⽰⽅式设计成这样的⽅式,通常需要⽤到这⼏个基本变量:pageSize(每个页⾯所显⽰的记录数)、pageCount(⼀共有多少个页⾯)、showPage(⽬前显⽰第⼏页)、recordCount(总的记录数),为了⽅便理解,画了⼀张图:如果想要把页⾯显⽰做成这样的效果,在这张图中pageSize=4,pageCount=3,showPage=1,recordCount=12。
思路是,如果要显⽰那个页⾯,就要先算出来每个页⾯第⼀条记录是所有记录中的第⼏条记录,假设每页的第⼀条记录是总记录中的第position条记录,那么position=(ShowPage - 1)×PageSize+1。
⽐如上图这个例⼦,如果要显⽰第⼀页,就要计算出第⼀页中的第⼀条记录是总的记录中的第⼀条记录;如果要显⽰第⼆页,就要计算出第⼆页中的第⼀条记录是总的记录中的第四条记录;如果要显⽰第三页,就要计算出第⼀页中的第⼀条记录是总的记录中的第九条记录。
在JSP中的核⼼代码为如下(⽤的数据库为MySQL):复制代码代码如下:<%! int pageSize=4;int pageCount;int showPage;%><!-- 连接数据库并从数据库中调取记录--><%Connection con;Statement sql;ResultSet rs;try{Class.forName("com.mysql.jdbc.Driver");}catch(ClassNotFoundException e){}try{con=DriverManager.getConnection("jdbc:mysql://localhost:3306/message board","root","123456"); sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY); //返回可滚动的结果集rs=sql.executeQuery("select * from messageinfo");//将游标移到最后⼀⾏st();//获取最后⼀⾏的⾏号int recordCount=rs.getRow();//计算分页后的总数pageCount=(recordCount%pageSize==0)?(lastRow/pageSize):(lastRow/pageSize+1);//获取⽤户想要显⽰的页数:String integer=request.getParameter("showPage");if(integer==null){integer="1";}try{showPage=Integer.parseInt(integer);}catch(NumberFormatException e){showPage=1;}if(showPage<=1){showPage=1;}if(showPage>=pageCount){showPage=pageCount;}//如果要显⽰第showPage页,那么游标应该移动到的position的值是:int position=(showPage-1)*pageSize+1;//设置游标的位置rs.absolute(position);//⽤for循环显⽰本页中应显⽰的的记录for(int i=1;i<=pageSize;i++){%><table><tr><th><%=rs.getString("UserName") %></th><td>发表于:<%=rs.getString("datetime") %></td></tr><tr ><th colspan="3"><textarea><%=rs.getString("content") %></textarea></th></tr></table><%rs.next();}rs.close();con.close();}catch(Exception e){e.printStackTrace();}%><br>第<%=showPage %>页(共<%=pageCount %>页)<br><a href="ShowMessages.jsp?showPage=1">⾸页</a><a href="ShowMessages.jsp?showPage=<%=showPage-1%>">上⼀页</a><% //根据pageCount的值显⽰每⼀页的数字并附加上相应的超链接for(int i=1;i<=pageCount;i++){%><a href="ShowMessages.jsp?showPage=<%=i%>"><%=i%></a><% }%><a href="ShowMessages.jsp?showPage=<%=showPage+1%>">下⼀页</a><a href="ShowMessages.jsp?showPage=<%=pageCount%>">末页</a><!-- 通过表单提交⽤户想要显⽰的页数 --><form action="" method="get">跳转到第<input type="text" name="showPage" size="4">页<input type="submit" name="submit" value="跳转"></form>运⾏结果如下(为了简化代码,已经⽹页布局相关代码去掉,此处仅指功能):可以跳转到⾸页、上⼀页、下⼀页、末页,可以⼿动在数字上指定页数,也可以在输⼊框中输⼊要显⽰的页数。
纯JSP分页代码//连接字符串Stringurl="jdbc:mysql://localhost/"+dbName+"?user="+userName+"&pa ssword="+userPasswd;Class.forName(driverName).newInstance();Connection connection=DriverManager.getConnection(url);Statement statement = connection.createStatement();//每页显示记录数int PageSize = 8;int StartRow = 0; //开始显示记录的编号int PageNo=0;//需要显示的页数int CounterStart=0;//每页页码的初始值int CounterEnd=0;//显示页码的最大值int RecordCount=0;//总记录数;int MaxPage=0;//总页数int PrevStart=0;//前一页int NextPage=0;//下一页int LastRec=0;int LastStartRecord=0;//最后一页开始显示记录的编号//获取需要显示的页数,由用户提交if(request.getParameter("PageNo")==null){ //如果为空,则表示第1页if(StartRow == 0){PageNo = StartRow + 1; //设定为1}}else{PageNo = Integer.parseInt(request.getParameter("PageNo")); //获得用户提交的页数StartRow = (PageNo - 1) * PageSize; //获得开始显示的记录编号}//因为显示页码的数量是动态变化的,假如总共有一百页,则不可能同时显示100个链接。
jspEL表达式结合JSTL标准标签实现分页<%@ page contentType="text/html; charset=GBK" %> <%@ taglib prefix="c" uri="" %><%@ taglib prefix="sql" uri="" %><%@taglib uri="" prefix="fmt"%><html><head><title>使用SQL标签</title></head><body bgcolor="white"><c:set var="noOfRows" value="10" /><sql:setDataSource driver ="sun.jdbc.odbc.JdbcOdbcDriver" url ="jdbc:odbc:accp" user="sa" password="" var="conn"/> <c:if test="${custList == null}"><sql:query var="custList" scope="session"sql="SELECT * FROM employee ORDER BY LName" dataSource="${conn}"/></c:if><c:choose><c:when test="${custList.rowCount == 0}">此处不再有其他客户...</c:when><c:otherwise><b>以下是客户列表:</b><p><table border="1"><th>姓氏</th><th>名字</th><th>年龄</th><c:forEach items="${custList.rows}" var="row" begin="${param.start}" end="${param.start + noOfRows - 1}"><tr><td><c:out value="${row.LName}" /></td> <td><c:out value="${row.FName}" /></td> <td><c:out value="${row.job_id}" /></td></tr></c:forEach></table></c:otherwise></c:choose><p><c:choose><c:when test="${param.start > 0}"><a href="foreachexample.jsp?start=<c:out value="${param.start - noOfRows}" />">上一页</a></c:when><c:otherwise>上一页</c:otherwise></c:choose><c:choose><c:when test="${param.start + noOfRows < custList.rowCount}"><a href="foreachexample.jsp?start=<c:out value="${param.start + noOfRows}" />">下一页</a></c:when><c:otherwise>下一页</c:otherwise></c:choose>共${custList.rowCount}条记录 共<fmt:formatNumber type="number" value="${custList.rowCount%noOfRows==0?custList.rowCount/ noOfRows:(custList.rowCount%noOfRows>4?(custList.rowCount /noOfRows):(custList.rowCount/noOfRows+1))}" maxFractionDigits="0"/> 页 第<fmt:formatNumber type="number" value="${(param.start%noOfRows==0?param.start/noOfRows:( param.start%noOfRows>4?(param.start/noOfRows):(param.start /noOfRows+1)))+1}" maxFractionDigits="0"/> 页</body></html>说明:这里使用到了标准标签库中SQL标签去查询数据记录。
1.1如何实现在基于J2EE Struts框架的Web应用中实现数据分页显示功能1、Web分页原理分页问题是一个非常普遍的问题,开发者几乎都会遇到。
因为Http的无状态性,每一次提交都是当作一个新的请求来处理,即使是换页,上一次的结果对下一次是没有影响的。
一般有三种实现分页的方式。
(1)每次取查询结果的所有数据,然后根据页码显示指定的纪录。
(2)根据页面只取一页数据,然后显示这一页,这里要构造sql语句。
(3)取一定页数的数据,就是前面两种的折中。
2、编程实现中的程序的实现方式——可以采用下面的几中形式(1)JSP+JavaBean(2)JSP+JavaBean+Tag标签库(3)利用Struts方式(JSP+Action +JavaBean)3、关于采用“JSP+JavaBean+Tag标签库”方式的实现示例(1)JSP页面1)引用标签库的*.tld<%@ taglib uri="/usertaglib/PageDataGuideBarWithAttrTag.tld"prefix="showGuideBar" %> 2)创建除为导航条提供初始参数的JavaBean的对象<jsp:useBean id="getShowGuideBarParamBeanID" scope="page"class="netbookbean.ViewHelper_GetShowGuideBarParam"/> 3)对ViewHelper_GetShowGuideBarParam.java的初始化方法的调用<%getShowGuideBarParamBeanID.guideBar_Init(pageContext);recordSet=getShowGuideBarParamBeanID.getRecordSet();%>(2)为标签库提供初始化参数<showGuideBar:PageDataGuideBarWithAttrTag currentShowPage="<%=newInteger(getShowGuideBarParamBeanID.getCurrentShowPage()).toString()%>"totalPageCount="<%=newInteger(getShowGuideBarParamBeanID.getTotalPageCount()).toString()%>"recordTotalCount="<%=newInteger(getShowGuideBarParamBeanID.getRecordTotalCount()).toString()%>"recordCounterPerPage="<%=newInteger(recordCounterPerPage).toString()%>" />(3)显示分页的数据(4)编程实现为导航条提供初始参数的JavaBean组件---ViewHelper_GetShowGuideBarParam.java(5)编程实现导航条功能的标签库----PageDataGuideBarWithAttrTag.java4、关于利用Struts方式(JSP+Action +JavaBean)方式的实现示例既然采用Struts,那自然离不了MVC,分页显示也是如此。
jsp中完整的分页显⽰和页⾯跳转功能实现的源代码<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030" import="java.util.*,entity.*"%><html><head><meta http-equiv="Content-Type" content="text/html; charset=GB18030"><title>Insert title here</title><script type="text/javascript">function submitPage(obj, evt){evt = (evt) ? evt : ((window.event) ? window.event : "")keyCode = evt.keyCode ? evt.keyCode : (evt.which ? evt.which : evt.charCode);if (keyCode == 13) {document.frmPage.submit();}}</script></head><body><form action="" method="post"><p><input type="button" value="新增" onClick="add()"><input type="button" value="修改" onClick="upd()"><input type="button" value="删除" onClick="del()"><input type="hidden" name="action" value="select"/></p><%List<Student> stuList = (List<Student>)request.getAttribute("stulist");if (stuList.size() != 0){%><table border="1" width="500" height="100"><tr><td> </td><td>学号</td><td>姓名</td><td>语⽂</td><td>数学</td><td>英语</td></tr><%/*翻页设定*/int PageSize; //⼀页显⽰的记录数int RowCount; //记录总数int PageCount;//总页数int intPage; //待显⽰页码int i,j;//设置每页显⽰的记录数PageSize = 2;//取得页码String strPage=request.getParameter( "page");if(strPage == null){//表明在QueryString中没有page这⼀个参数,此时显⽰第⼀页数据intPage = 1;//将字符串转换成整型intPage=Integer.parseInt(strPage);if( intPage < 1 ){intPage=1;}}//获取记录总数RowCount = stuList.size();//记算总页数PageCount = ( RowCount + PageSize - 1 ) / PageSize;//调整待显⽰的页码if( intPage > PageCount){intPage = PageCount;}//将记录指针定位到待显⽰页的第⼀条记录上i = ( intPage - 1 ) * PageSize;%><%for ( j = i ; j < RowCount && j < i + PageSize ; j++ ){Student stu = stuList.get(j);%><tr><td><input type="radio" name="selStu" value="<%=stu.getStuNum()%>"/></td><td><%=stu.getStuNum() %></td><td><%=stu.getStuName() %></td><td><%=stu.getChScore() %></td><td><%=stu.getMathScore() %></td><td><%=stu.getEnScore() %></td></tr><%}%><tr align=center><td colspan=6 align=center><form name="frmPage" action="SelectStudent" method="get">回车转到第 <input type="text" name="page" size="3" onKeyPress="submitPage(this,event)" />页 </form>第 <%=intPage%> 页共 <%=PageCount%> 页共有 <%=RowCount%> 条记录<%if(intPage> 1){%> <a href="SelectStudent?page=<%=intPage-1%>">上⼀页 </a> <%}%> <%if(intPage <PageCount){%> <a href="SelectStudent?page=<%=intPage+1%>">下⼀页 </a> <%}%></form><%}else{System.out.println("学⽣信息库中没有数据"); }%></body></html>。
JavaWeb简单的分页显⽰实例代码本⽂通过两个⽅法:(1)计算总的页数。
(2)查询指定页数据,实现简单的分页效果。
思路:⾸先得在 DAO 对象中提供分页查询的⽅法,在控制层调⽤该⽅法查到指定页的数据,在表⽰层通过 EL 表达式和JSTL 将该页数据显⽰出来。
先给⼤家展⽰下效果图:题外话:该分页显⽰是⽤ “表⽰层-控制层-DAO层-数据库”的设计思想实现的,有什么需要改进的地⽅⼤家提出来,共同学习进步。
废话不多说了,开始进⼊主题,详细步骤如下所⽰:1.DAO层-数据库JDBCUtils 类⽤于打开和关闭数据库,核⼼代码如下:import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;public class JDBCUtils {private Connection conn=null;private PreparedStatement pstmt=null;/*** connect 连接数据库* @return*/public Connection connect(){String user="root";String password="1234";String driverClass = "com.mysql.jdbc.Driver";String jdbcUrl = "jdbc:mysql://localhost:3306/book";try {Class.forName(driverClass);conn = DriverManager.getConnection(jdbcUrl, user, password);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return conn;}/*** close 关闭数据库* @param conn* @param pstmt* @param resu*/public void close(Connection conn,PreparedStatement pstmt,ResultSet result){if(conn != null){try {conn.close();} catch (SQLException e) {// TODO Auto-generated catch block}}if(pstmt != null){try {pstmt.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(result != null){try {result.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}UserDao 类中的⽅法 getPage() 和⽅法 listUser() 分别⽤来计算总页数和查询指定页的数据,核⼼代码如下:import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import com.db.JDBCUtils;public class UserDao {/*** 计算总的页数* @return*/public int getPage(){int recordCount=0,t1=0,t2=0;PreparedStatement pstmt=null;ResultSet result=null;JDBCUtils jdbc=new JDBCUtils();Connection conn=jdbc.connect();String sql="select count(*) from books";try {pstmt=conn.prepareStatement(sql);result=pstmt.executeQuery();result.next();recordCount=result.getInt(1);t1=recordCount%5;t2=recordCount/5;} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{jdbc.close(conn, pstmt, result);}if(t1 != 0){t2=t2+1;}return t2;}/*** 查询指定页的数据* @param pageNo* @return*/public List<User> listUser(int pageNo){PreparedStatement pstmt=null;ResultSet result=null;List<User> list=new ArrayList<User>();int pageSize=5;int page=(pageNo-1)*5;JDBCUtils jdbc=new JDBCUtils();Connection conn=jdbc.connect();String sql="select * from books order by id limit ?,?";try {pstmt=conn.prepareStatement(sql);pstmt.setInt(1, page);pstmt.setInt(2, pageSize);result=pstmt.executeQuery();while(result.next()){User user=new User();user.setId(result.getInt(1));user.setName(result.getString(2));user.setNumber(result.getString(3));list.add(user);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{jdbc.close(conn, pstmt, result);}return list;}}User 类⽤于存储查询到的数据,核⼼代码如下:public class User {private int id;private String name;private String number;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) { = name;}public String getNumber() {return number;}public void setNumber(String number) {this.number = number;}}2.控制层ListUser 类内部调⽤ UserDao 对象查询数据并指派页⾯显⽰数据,核⼼代码如下:import java.io.IOException;import java.io.PrintWriter;import java.util.ArrayList;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import er;import erDao;public class ListUser extends HttpServlet {public ListUser() {super();}public void destroy() {super.destroy(); // Just puts "destroy" string in 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 {response.setCharacterEncoding("utf-8");int pageNo = 1;UserDao userdao=new UserDao();List<User> lists=new ArrayList<User>();String pageno=request.getParameter("pageNos");if(pageno != null){pageNo=Integer.parseInt(pageno);}lists=userdao.listUser(pageNo);int recordCount=userdao.getPage();request.setAttribute("recordCount", userdao.getPage());request.setAttribute("listss", lists);request.setAttribute("pageNos", pageNo);request.getRequestDispatcher("userlist.jsp").forward(request, response);}public void init() throws ServletException {// Put your code here}}3.表⽰层输出页⾯ userlist.jsp ,使⽤ EL 和 JSTL 输出查询结果,核⼼代码如下:<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="/jsp/jstl/core" %><%@ taglib uri="/jsp/jstl/fmt" prefix="fmt"%><%@ taglib uri="/jsp/jstl/functions" prefix="fn"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>My JSP 'userlist.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">--><style type="text/css">th,td{width: 150px;border: 2px solid gray;text-align: center;}body{text-align: center;}a{text-decoration: none;}table {border-collapse: collapse;}</style></head><body><h2 align="center">图书信息</h2><table align="center"><tr><td>书号</td><td>书名</td><td>库存量</td></tr></table><table align="center"><c:forEach items="${listss}" var="person"><tr><td class="hidden-480">${person.id}</td><td class="hidden-480">${ }</td><td class="hidden-480">${person.number }</td></tr></c:forEach></table><br><c:if test="${pageNos>1 }"><a href="ListUser?pageNos=1" >⾸页</a><a href="ListUser?pageNos=${pageNos-1 }">上⼀页</a></c:if><c:if test="${pageNos <recordCount }"><a href="ListUser?pageNos=${pageNos+1 }">下⼀页</a><a href="ListUser?pageNos=${recordCount }">末页</a></c:if><form action="ListUser"><h4 align="center">共${recordCount}页  <input type="text" value="${pageNos}" name="pageNos" size="1">页<input type="submit" value="到达"></h4></form></body></html>以上所述是⼩编给⼤家介绍的Java Web 简单的分页显⽰实例代码,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。
如何在JavaScript中实现数据的分页和加载更多数据分页和加载更多是前端开发中非常常见的功能,特别是在需要展示大量数据的情况下,常常需要将数据进行分页展示,并且提供加载更多的功能来满足用户的浏览需求。
在JavaScript中实现数据分页和加载更多可以通过一些常见的方法和技巧来实现,接下来我们将介绍如何在JavaScript中实现数据的分页和加载更多的功能。
一、数据分页的基本原理数据分页的基本原理是将大量的数据,按照一页显示的数据量,进行分割成多页进行展示。
其中包括两个关键因素,一是数据量的分割,二是页面的展示控制。
在JavaScript中,我们可以通过对数据进行分片和处理,并且通过一些分页插件或者自定义的分页逻辑来进行页面的展示。
二、实现数据分页的步骤要实现数据的分页,我们需要按照以下步骤来进行。
1.获取数据首先,我们需要获取服务器端的数据。
这可以通过Ajax请求,或者使用一些前端模拟数据来模拟实现。
一般来说,我们会得到一个包含所有数据的数组或者对象。
2.分割数据接下来,我们需要将获取到的数据进行分割。
我们可以定义一个固定的页大小,比如每页显示10条数据。
然后将整个数据集按照页大小进行分割,形成一个包含多个小数组的大数组,每个小数组即表示一页的数据。
3.数据展示最后,我们需要将分割后的数据进行展示。
这可以通过动态生成DOM元素,或者使用一些前端框架来进行数据的渲染和展示。
三、加载更多的实现方法加载更多功能是用户在浏览数据时最常用的功能之一。
当用户滚动到页面底部时,自动加载下一页的数据,或者点击按钮来手动加载更多数据。
在JavaScript中,我们可以通过监听滚动事件或者点击事件来实现加载更多功能。
1.监听滚动事件我们可以通过JavaScript监听页面的滚动事件,当页面滚动到底部时,自动加载下一页的数据。
这可以通过监听window对象的scroll 事件来实现。
在scroll事件的回调函数中,我们可以判断页面滚动的位置是否已经到达底部,并且加载下一页的数据。
<html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><meta name="Copyright" content="懒人图库/" /><meta name="description" content="学会偷懒,并懒出境界是提高工作效率最有效的方法!" /> <meta content="懒人图库" name="keywords" /><title>懒人图库</title><style>body {font-size: 12px;}/* Pages Main Tyle */.pages {color: #000000;cursor: default;font-size: 10px;font-family: Tahoma, Verdana;padding: 3px 0px 3px 0px;}.pages .count, .pages .number, .pages .arrow {color: #000000;font-size: 10px;background-color: #F7F7F7;border: 1px solid #CCCCCC;}/* Page and PageCount Style */.pages .count {font-weight: bold;border-right: none;padding: 2px 10px 1px 10px;}/* Mode 0,1,2 Style (Number) */.pages .number {font-weight: normal;padding: 2px 10px 1px 10px;}.pages .number a, .pages .number span {font-size: 10px;}.pages .number span {color: #999999;margin: 0px 3px 0px 3px;}.pages .number a {color: #000000;text-decoration: none;}.pages .number a:hover {color: #0000ff;}/* Mode 3 Style (Arrow) */.pages .arrow {font-weight: normal;padding: 0px 5px 0px 5px;}.pages .arrow a, .pages .arrow span {font-size: 10px;font-family: Webdings;}.pages .arrow span {color: #999999;margin: 0px 5px 0px 5px;}.pages .arrow a {color: #000000;text-decoration: none;}.pages .arrow a:hover {color: #0000ff;}/* Mode 4 Style (Select) */.pages select, .pages input {color: #000000;font-size: 10px;font-family: Tahoma, Verdana;}/* Mode 5 Style (Input) */.pages .input input.ititle, .pages .input input.itext, .pages .input input.icount { color: #666666;font-weight: bold;background-color: #F7F7F7;border: 1px solid #CCCCCC;}.pages .input input.ititle {width: 70px;text-align: right;border-right: none;}.pages .input input.itext {width: 25px;color: #000000;text-align: right;border-left: none;border-right: none;}.pages .input input.icount {width: 35px;text-align: left;border-left: none;}.pages .input input.ibutton {height: 17px;color: #FFFFFF;font-weight: bold;font-family: Verdana;background-color: #999999;border: 1px solid #666666;padding: 0px 0px 2px 1px;margin-left: 2px;cursor: hand;}</style><script language="JavaScript"><!--/*showPages v1.1=================================Infomation----------------------Author : LapuasiE-Mail : lapuasi@Web : Date : 2005-11-17Example----------------------var pg = new showPages('pg');pg.pageCount = 12; //定义总页数(必要)pg.argName = 'p'; //定义参数名(可选,缺省为page) pg.printHtml(); //显示页数Supported in Internet Explorer, Mozilla Firefox*/function showPages(name) { //初始化属性 = name; //对象名称this.page = 1; //当前页数this.pageCount = 1; //总页数this.argName = 'page'; //参数名this.showTimes = 1; //打印次数}showPages.prototype.getPage = function(){ //丛url获得当前页数,如果变量重复只获取最后一个var args = location.search;var reg = new RegExp('[\?&]?' + this.argName + '=([^&]*)[&$]?', 'gi');var chk = args.match(reg);this.page = RegExp.$1;}showPages.prototype.checkPages = function(){ //进行当前页数和总页数的验证if (isNaN(parseInt(this.page))) this.page = 1;if (isNaN(parseInt(this.pageCount))) this.pageCount = 1;if (this.page < 1) this.page = 1;if (this.pageCount < 1) this.pageCount = 1;if (this.page > this.pageCount) this.page = this.pageCount;this.page = parseInt(this.page);this.pageCount = parseInt(this.pageCount);}showPages.prototype.createHtml = function(mode){ //生成html代码var strHtml = '', prevPage = this.page - 1, nextPage = this.page + 1;if (mode == '' || typeof(mode) == 'undefined') mode = 0;switch (mode) {case 0 : //模式1 (页数,首页,前页,后页,尾页)strHtml += '<span class="count">Pages: ' + this.page + ' / ' + this.pageCount + '</span>';strHtml += '<span class="number">';if (prevPage < 1) {strHtml += '<span title="First Page">«</span>';strHtml += '<span title="Prev Page">‹</span>';} else {strHtml += '<span title="First Page"><a href="javascript:' + + '.toPage(1);">«</a></span>';strHtml += '<span title="Prev Page"><a href="javascript:' + +'.toPage(' + prevPage + ');">‹</a></span>';}for (var i = 1; i <= this.pageCount; i++) {if (i > 0) {if (i == this.page) {strHtml += '<span title="Page ' + i + '">[' + i + ']</span>';} else {strHtml += '<span title="Page ' + i + '"><a href="javascript:' + + '.toPage(' + i + ');">[' + i + ']</a></span>';}}}if (nextPage > this.pageCount) {strHtml += '<span title="Next Page">›</span>';strHtml += '<span title="Last Page">»</span>';} else {strHtml += '<span title="Next Page"><a href="javascript:' + + '.toPage(' + nextPage + ');">›</a></span>';strHtml += '<span title="Last Page"><a href="javascript:' + + '.toPage(' + this.pageCount + ');">»</a></span>';}strHtml += '</span><br />';break;case 1 : //模式1 (10页缩略,首页,前页,后页,尾页)strHtml += '<span class="count">Pages: ' + this.page + ' / ' + this.pageCount + '</span>';strHtml += '<span class="number">';if (prevPage < 1) {strHtml += '<span title="First Page">«</span>';strHtml += '<span title="Prev Page">‹</span>';} else {strHtml += '<span title="First Page"><a href="javascript:' + + '.toPage(1);">«</a></span>';strHtml += '<span title="Prev Page"><a href="javascript:' + + '.toPage(' + prevPage + ');">‹</a></span>';}if (this.page % 10 ==0) {var startPage = this.page - 9;} else {var startPage = this.page - this.page % 10 + 1;}if (startPage > 10) strHtml += '<span title="Prev 10 Pages"><a href="javascript:' + + '.toPage(' + (startPage - 1) + ');">...</a></span>';for (var i = startPage; i < startPage + 10; i++) {if (i > this.pageCount) break;if (i == this.page) {strHtml += '<span title="Page ' + i + '">[' + i + ']</span>';} else {strHtml += '<span title="Page ' + i + '"><a href="javascript:' + + '.toPage(' + i + ');">[' + i + ']</a></span>';}}if (this.pageCount >= startPage + 10) strHtml += '<span title="Next 10 Pages"><a href="javascript:' + + '.toPage(' + (startPage + 10) + ');">...</a></span>';if (nextPage > this.pageCount) {strHtml += '<span title="Next Page">›</span>';strHtml += '<span title="Last Page">»</span>';} else {strHtml += '<span title="Next Page"><a href="javascript:' + + '.toPage(' + nextPage + ');">›</a></span>';strHtml += '<span title="Last Page"><a href="javascript:' + + '.toPage(' + this.pageCount + ');">»</a></span>';}strHtml += '</span><br />';break;case 2 : //模式2 (前后缩略,页数,首页,前页,后页,尾页)strHtml += '<span class="count">Pages: ' + this.page + ' / ' + this.pageCount + '</span>';strHtml += '<span class="number">';if (prevPage < 1) {strHtml += '<span title="First Page">«</span>';strHtml += '<span title="Prev Page">‹</span>';} else {strHtml += '<span title="First Page"><a href="javascript:' + + '.toPage(1);">«</a></span>';strHtml += '<span title="Prev Page"><a href="javascript:' + + '.toPage(' + prevPage + ');">‹</a></span>';}if (this.page != 1) strHtml += '<span title="Page 1"><a href="javascript:' + + '.toPage(1);">[1]</a></span>';if (this.page >= 5) strHtml += '<span>...</span>';if (this.pageCount > this.page + 2) {var endPage = this.page + 2;} else {var endPage = this.pageCount;}for (var i = this.page - 2; i <= endPage; i++) {if (i > 0) {if (i == this.page) {strHtml += '<span title="Page ' + i + '">[' + i + ']</span>';} else {if (i != 1 && i != this.pageCount) {strHtml += '<span title="Page ' + i + '"><a href="javascript:' + + '.toPage(' + i + ');">[' + i + ']</a></span>';}}}}if (this.page + 3 < this.pageCount) strHtml += '<span>...</span>';if (this.page != this.pageCount) strHtml += '<span title="Page ' + this.pageCount + '"><a href="javascript:' + + '.toPage(' + this.pageCount + ');">[' + this.pageCount + ']</a></span>';if (nextPage > this.pageCount) {strHtml += '<span title="Next Page">›</span>';strHtml += '<span title="Last Page">»</span>';} else {strHtml += '<span title="Next Page"><a href="javascript:' + + '.toPage(' + nextPage + ');">›</a></span>';strHtml += '<span title="Last Page"><a href="javascript:' + + '.toPage(' + this.pageCount + ');">»</a></span>';}strHtml += '</span><br />';break;case 3 : //模式3 (箭头样式,首页,前页,后页,尾页) (only IE)strHtml += '<span class="count">Pages: ' + this.page + ' / ' + this.pageCount + '</span>';strHtml += '<span class="arrow">';if (prevPage < 1) {strHtml += '<span title="First Page">9</span>';strHtml += '<span title="Prev Page">7</span>';} else {strHtml += '<span title="First Page"><a href="javascript:' + + '.toPage(1);">9</a></span>';strHtml += '<span title="Prev Page"><a href="javascript:' + + '.toPage(' + prevPage + ');">7</a></span>';}if (nextPage > this.pageCount) {strHtml += '<span title="Next Page">8</span>';strHtml += '<span title="Last Page">:</span>';} else {strHtml += '<span title="Next Page"><a href="javascript:' + + '.toPage(' + nextPage + ');">8</a></span>';strHtml += '<span title="Last Page"><a href="javascript:' + + '.toPage(' + this.pageCount + ');">:</a></span>';}strHtml += '</span><br />';break;case 4 : //模式4 (下拉框)if (this.pageCount < 1) {strHtml += '<select name="toPage" disabled>';strHtml += '<option value="0">No Pages</option>';} else {var chkSelect;strHtml += '<select name="toPage" onchange="' + + '.toPage(this);">';for (var i = 1; i <= this.pageCount; i++) {if (this.page == i) chkSelect=' selected="selected"';else chkSelect='';strHtml += '<option value="' + i + '"' + chkSelect + '>Pages: ' + i + ' / ' + this.pageCount + '</option>';}}strHtml += '</select>';break;case 5 : //模式5 (输入框)strHtml += '<span class="input">';if (this.pageCount < 1) {strHtml += '<input type="text" name="toPage" value="No Pages" class="itext" disabled="disabled">';strHtml += '<input type="button" name="go" value="GO" class="ibutton" disabled="disabled"></option>';} else {strHtml += '<input type="text" value="Input Page:" class="ititle" readonly="readonly">';strHtml += '<input type="text" id="pageInput' + this.showTimes + '" value="' + this.page + '" class="itext" title="Input page" onkeypress="return ' + + '.formatInputPage(event);" onfocus="this.select()">';strHtml += '<input type="text" value=" / ' + this.pageCount + '" class="icount" readonly="readonly">';strHtml += '<input type="button" name="go" value="GO" class="ibutton" onclick="' + + '.toPage(document.getElementById(\'pageInput' + this.showTimes + '\').value);"></option>';}strHtml += '</span>';break;default :strHtml = 'Javascript showPage Error: not find mode ' + mode;break;}return strHtml;}showPages.prototype.createUrl = function (page) { //生成页面跳转urlif (isNaN(parseInt(page))) page = 1;if (page < 1) page = 1;if (page > this.pageCount) page = this.pageCount;var url = location.protocol + '//' + location.host + location.pathname;var args = location.search;var reg = new RegExp('([\?&]?)' + this.argName + '=[^&]*[&$]?', 'gi');args = args.replace(reg,'$1');if (args == '' || args == null) {args += '?' + this.argName + '=' + page;} else if (args.substr(args.length - 1,1) == '?' || args.substr(args.length - 1,1) == '&') { args += this.argName + '=' + page;} else {args += '&' + this.argName + '=' + page;}return url + args;}showPages.prototype.toPage = function(page){ //页面跳转var turnTo = 1;if (typeof(page) == 'object') {turnTo = page.options[page.selectedIndex].value;} else {turnTo = page;}self.location.href = this.createUrl(turnTo);}showPages.prototype.printHtml = function(mode){ //显示html代码this.getPage();this.checkPages();this.showTimes += 1;document.write('<div id="pages_' + + '_' + this.showTimes + '" class="pages"></div>');document.getElementById('pages_' + + '_' + this.showTimes).innerHTML = this.createHtml(mode);}showPages.prototype.formatInputPage = function(e){ //限定输入页数格式var ie = navigator.appName=="Microsoft Internet Explorer"?true:false;if(!ie) var key = e.which;else var key = event.keyCode;if (key == 8 || key == 46 || (key >= 48 && key <= 57)) return true;return false;}//--></script></head><body><p><script language="JavaScript"><!--var pg = new showPages('pg');pg.pageCount =12; // 定义总页数(必要)//pg.argName = 'p'; // 定义参数名(可选,默认为page)document.write('<br>Show Times: ' + pg.showTimes + ', Mood Default');pg.printHtml();document.write('<br>Show Times: ' + pg.showTimes + ', Mood 0');pg.printHtml(0);document.write('<br>Show Times: ' + pg.showTimes + ', Mood 1');pg.printHtml(1);document.write('<br>Show Times: ' + pg.showTimes + ', Mood 2');pg.printHtml(2);document.write('<br>Show Times: ' + pg.showTimes + ', Mood 3 (only IE)');pg.printHtml(3);document.write('<br>Show Times: ' + pg.showTimes + ', Mood 4');pg.printHtml(4);document.write('<br>Show Times: ' + pg.showTimes + ', Mood 5');pg.printHtml(5);//--></script></p><p>查找更多代码,请访问:<a href="" target="_blank">懒人图库</a></p></body></html>。
纯js分页代码(简洁实⽤)代码如下://每页显⽰字数PageSize=5000;//分页模式flag=2;//1:根据字数⾃动分页 2:根据[NextPage]分页//默认页startpage = 1;//导航显⽰样式 0:常规 1:直接 3:下拉TopShowStyle = 1;DownShowStyle = 0;var currentSet,CutFlag,TotalByte,PageCount,key,tempText,tempPage;key="";currentSet=0;var Text=xmlArticle.selectSingleNode("//Content").text;TotalByte=Text.length;if (flag==1){PageCount=Math.round(TotalByte/PageSize);if(parseFloat("0."+TotalByte%PageSize)>0){if(parseFloat("0."+TotalByte%PageSize)<0.5){PageCount=PageCount+1;}}var PageNum=new Array(PageCount+1);var PageTitle=new Array(PageCount+1);PageNum[0]=0;PageTitle[0]="";var sDrv1,sDrv2,sDrv3,sDrv4,sFlag;var sDrvL,sTemL;var sTem1,sTem2,k;sFlag=0;for(j=1;j<PageCount+1;j++){PageNum[j]=PageNum[j-1]+PageSize;PageTitle[j]="";//alert(j);sDrv1="<br>";sDrv2="<BR>";sDrv3="<Br>";sDrv4="<bR>";sDrvL=sDrv1.length;for(k=PageNum[j];k<=TotalByte;k++){sTem1=Text.substring(PageNum[j]-sDrvL,k);sTemL=sTem1.length;sTem2=sTem1.substring(sTemL-sDrvL,sTemL)if (sTem2==sDrv1 || sTem2==sDrv2 || sTem2==sDrv3 || sTem2==sDrv4){sFlag=sFlag+1;PageNum[j]=k;break;}}if (PageNum[j]>TotalByte){break;}}if (j<PageCount){PageNum.length=j;PageCount=j}if (PageCount>1&&sFlag>1&&PageCount<sFlag){PageCount=sFlag+1;}}else{//⼿动分页var j,sFlag,PageCount,sText;var sTitleFlag;var PageNum=new Array();var PageTitle=new Array();PageSize=0;j=1;PageNum[0]=-10;PageTitle[0]="";sFlag=0;sText=Text;do{sText=Text.substring(PageNum[j-1]+10,TotalByte);sFlag=sText.indexOf("[NextPage");if (sText.substring(sFlag+9,sFlag+10)=="="){sTitleFlag=sText.indexOf("]",sFlag);PageTitle[j]=sText.substring(sFlag+10,sTitleFlag);}else{PageTitle[j]="";}if (sFlag>0){PageNum[j]=sFlag+PageNum[j-1]+10;}else{PageNum[j]=TotalByte;}j+=1;}while (PageNum[j-1]<TotalByte);PageCount=j-1;}function text_pagination(Page){var Output,Byte;if(Page==null){Page=1;}Output="";Output=Output+"<table width=100% height=30 border=0 align=center cellpadding=0 cellspacing=0>";Output=Output+"<tr>";Output=Output+"<td height=1 background=Images/DotLine.gif></td>";Output=Output+"</tr>";//头部功能导航条Output=Output+"<tr>";//正⽂查找Output=Output+"<td align=left bgcolor=#f0faff width='40%'> ";Output=Output+"<input type=text name=keys onchange='key=this.value' size=12> <input type=button name=search value='查找正⽂' onclick='searchkey();' style='width:60'>";Output=Output+"<td align=right bgcolor=#f0faff>";//页码显⽰⽅式⼀//第x页:分页标题if (Page==0 || PageCount==0){Output=Output+"当前是:<font color=red>全⽂显⽰</font>" ;}else{if(TotalByte>PageSize){Byte=PageNum[Page]-PageNum[Page-1]}else{Byte=TotalByte}; Output=Output+"第 <font color=red>"+Page+"</font> 页";if (PageTitle[Page]!=""){Output=Output+":<font color=800000>"+PageTitle[Page]+"</font>";}Output+=' ';}//显⽰⽅式⼆//下拉菜单选择//if (PageCount>0)//{// Output=Output+Article_PageNav(2,Page);// Output=Output+" </td>";//}//显⽰⽅式三//页码选择列表//Output=Output+"<td align=right bgcolor=#f0faff>";//Output=Output+Article_PageNav(0,Page);//Output=Output+"</td>";Output=Output+"</tr>";Output=Output+"<tr>";Output=Output+"<td height=1 background=Images/DotLine.gif></td>";Output=Output+"</tr>";Output=Output+"</table>";//显⽰正⽂if(Page==0) {//不分页tempText=Text;}else{//分页if (flag==1)//⾃动分页{tempText=Text.substring(PageNum[Page-1],PageNum[Page]);}else{//⼿动分页if (PageTitle[Page-1].length==0){tempText=Text.substring(PageNum[Page-1]+10,PageNum[Page]);}else{tempText=Text.substring(PageNum[Page-1]+11+PageTitle[Page-1].length,PageNum[Page]); }}}//布置内容Output=Output+"<div align=center>";Output=Output+Article_PageNav(TopShowStyle,Page);Output=Output+"</div>";Output=Output+"<div id=world>";Output=Output+"</div>";Output=Output+"<br>";Output=Output+"<div align=center>";Output=Output+Article_PageNav(DownShowStyle,Page);Output=Output+"</div>";article.innerHTML = Output;if (Page>1){document.location.href='#top';}eval(document.all.keys).value=key;if (key!=""){searchkey();}}function searchkey(){//正⽂查找函数h="<font class="keyworld">";f="</font>";keyset=new Array();key=document.all.keys.value;if (key==""){alert("请输⼊关键字!");return;}else{keyset[0]=tempText.indexOf(key,0);if (keyset[0]<0){return;}elsetemp=tempText.substring(0,keyset[0]);temp=temp+h+key+f;temp2=tempText.substring(keyset[0]+key.length,tempText.length);for (i=1;i<tempText.length;i++) {keyset[i]=tempText.indexOf(key,keyset[i-1]+key.length);if(keyset[i]<0){temp=temp+tempText.substring(keyset[i-1]+key.length,tempText.length);break;}else{temp=temp+tempText.substring(keyset[i-1]+key.length,keyset[i])+h+key+f;}}world.innerHTML = temp;}}function Article_PageNav(ShowStyle,Page){//分页码显⽰函数//参数为调⽤样式,0=简单样式,1=标准样式var temp="";if (ShowStyle==0)//简单样式{tempPage=Page;if(TotalByte>PageSize){if (Page-4<=1){temp=temp+"<font face=webdings color=#999999>9</font>";if (Page<=1){temp=temp+"<font face=webdings color=#999999>7</font>";}else{temp=temp+"<a href=javascript:text_pagination("+(Page-1)+")><font face=webdings>7</font></a>";}if (PageCount>10){for(i=1;i<8;i++){if (i==Page){temp=temp+"<font color=red>"+i+"</font> ";}else{temp=temp+"<a href=javascript:text_pagination("+i+") >"+i+"</a>"+" ";}}temp=temp+" ...";}else{for(i=1;i<PageCount+1;i++){if (i==Page){temp=temp+"<font color=red>"+i+"</font> ";}else{temp=temp+"<a href=javascript:text_pagination("+i+") >"+i+"</a>"+" ";}}}if (Page==PageCount){temp=temp+"<font face=webdings color=#999999>8</font>";}else{temp=temp+"<a href=javascript:text_pagination("+(Page+1)+")><font face=webdings>8</font></a>";}if(PageCount<10){temp=temp+"<font face=webdings color=#999999>:</font>";}else{temp=temp+"<a href=javascript:text_pagination("+PageCount+")><font face=webdings>:</font></a>";}}else if(Page+4<=PageCount){temp=temp+"<a href=javascript:text_pagination(1)><font face=webdings>9</font></a>";temp=temp+"<a href=javascript:text_pagination("+(Page-1)+")><font face=webdings>7</font></a>";if (PageCount>10){temp=temp+"..";for(i=Page-4;i<Page+4;i++){if (i==Page){temp=temp+"<font color=red>"+i+"</font> ";}else{temp=temp+"<a href=javascript:text_pagination("+i+") >"+i+"</a>"+" ";}}temp=temp+" ..";}else{for(i=1;i<PageCount+1;i++){if (i==Page){temp=temp+"<font color=red>"+i+"</font> ";}else{temp=temp+"<a href=javascript:text_pagination("+i+") >"+i+"</a>"+" ";}}}if (Page==PageCount){temp=temp+"<font face=webdings color=#999999>8</font>";}else{temp=temp+"<a href=javascript:text_pagination("+(Page+1)+")><font face=webdings>8</font></a>";}temp=temp+"<a href=javascript:text_pagination("+PageCount+")><font face=webdings>:</font></a>";}else{temp=temp+"<a href=javascript:text_pagination(1)><font face=webdings>9</font></a>";temp=temp+"<a href=javascript:text_pagination("+(Page-1)+")><font face=webdings>7</font></a>"; temp=temp+".."for(i=Page-2;i<PageCount+1;i++){if (i==Page){temp=temp+"<font color=red>"+i+"</font> ";}else{temp=temp+"<a href=javascript:text_pagination("+i+") >"+i+"</a>"+" ";}}if (Page==PageCount){temp=temp+"<font face=webdings color=#999999>8</font>";}else{temp=temp+"<a href=javascript:text_pagination("+(Page+1)+")><font face=webdings>8</font></a>";}temp=temp+"<font face=webdings color=#999999>:</font>";}}else{temp=temp+"<font color=red>1</font> ";}temp=temp+" <a href=javascript:text_pagination(0)>显⽰全部</a>"}else if (ShowStyle==1)//标准样式{if(TotalByte>PageSize){if(Page!=0){if(Page!=1){temp=temp+"<a href='#top' onclick=javascript:text_pagination("+(Page-1)+")><font color=3366cc>[上⼀页]</font></a> ";}}}for (i=1;i<PageCount+1 ;i++ ){if (Page==i){temp=temp+"<font color=800000>["+i+"]</font> ";}else{temp=temp+"<a href='#top' onclick=javascript:text_pagination("+i+")><font color=3366cc>["+i+"]</font></a> ";}}temp=temp+"<a name='foot'></a>";if(TotalByte>PageSize){if(Page!=0){if(Page!=PageCount){temp=temp+"<a href='#top' onclick=javascript:text_pagination("+(Page+1)+")> <font color=3366cc>[下⼀页]</font></a>";}}}temp=temp+" <a href=javascript:text_pagination(0)><font color=3366cc>显⽰全部</font></a>"}else if (ShowStyle==2)//下拉菜单样式{temp=temp+'<select onchange="text_pagination(this.value)">'for (i=1;i<PageCount+1 ;i++ ){if (Page==i){temp=temp+"<option value='"+i+"' selected style='color:red'>第 "+i+" 页"}else{temp=temp+"<option value='"+i+"'>第 "+i+" 页";}if (PageTitle[i].length!=0){temp=temp+':'+PageTitle[i];}temp=temp+"</option>";}temp=temp+"</select>";}return (temp);}//默认页text_pagination(startpage);--------------分页js代码结束--------------------------html页⾯,调⽤分页js------------------复制代码代码如下:<HTML><HEAD><TITLE>js分页</TITLE><META http-equiv=Content-Type content="text/html; charset=gb2312"></HEAD><BODY bottomMargin=0 leftMargin=0 topMargin=0 rightMargin=0><TABLE cellSpacing=1 cellPadding=5 width="95%" align=centerborder=0><TBODY><TR><TD><xml id=xmlArticle><Article><Info><Content><![CDATA[⼤家来试验分页哦~~~~~[NextPage]我分~~~[NextPage]我再分[NextPage]分分分]]></Content></Info></Article></xml><!--正⽂分页Js--><SCRIPT language=Javascriptsrc="attachments/month_0607/j200674214834.js"></SCRIPT></TD></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE>。
一、引言随着互联网技术的发展和普及,前端开发在全球信息湾和应用程序中扮演着越来越重要的角色。
前端分页是前端开发中常见的需求之一,通过分页可以将大量数据分割成多个页面,提高数据展示效率和用户体验。
本文将介绍如何使用javascript实现前端分页效果的方法。
二、基本原理在进行前端分页操作时,需要做到以下几点:获取总数据量和每页显示的数量;根据总数据量和每页数量计算出总页数;根据当前页码和每页数量,截取相应的数据进行展示。
三、实现步骤1. 获取总数据量和每页显示的数量在实现前端分页效果时,首先需要获取总数据量和每页显示的数量。
总数据量通常来自后端接口返回的数据或者在前端进行模拟数据。
每页显示的数量由业务需求确定,可以在代码中进行指定。
2. 计算总页数根据获取到的总数据量和每页显示的数量,可以通过简单的算术运算得到总页数。
如果总数据量为100条,每页显示10条数据,则总页数为100/10=10。
3. 根据当前页码截取数据在进行分页展示时,需要根据当前页码和每页显示的数量来截取相应的数据进行展示。
可以通过数组的slice方法来实现数据的截取。
4. 分页组件的实现为了方便使用,可以将上述步骤封装成一个独立的分页组件。
该组件可以接受总数据量、每页数量等参数,同时提供页码切换、数据截取等功能。
四、代码示例下面是一个简单的javascript代码示例,用于实现前端分页效果:```javascript// 假设有一个包含100条数据的数组const data = Array.from({ length: 100 }, (v, k) => k + 1);// 每页显示10条数据const pageSize = 10;// 根据页码和每页数量进行数据截取function getPageData(pageNum) {const start = (pageNum - 1) * pageSize;const end = start + pageSize;return data.slice(start, end);}// 测试console.log(getPageData(1)); // 第1页数据console.log(getPageData(2)); // 第2页数据// ...```五、总结通过上述步骤和代码示例,我们可以实现一个简单的前端分页效果。
javascript分页显⽰//根据条件查找数据list = Stdqj.FindAll(where, "ID desc", "", (pageindex - 1) * 15, 15);// 根据list查找的条件,查找list的总数(count)ViewBag.total = Stdqj.FindCount(where);//在传递参数中传递pageindex//获取当前pageindex的值ViewBag.pageindex = pageindex;}return View(list);<div id="pager"><a href="javascript:;" onclick="goPage(1)">⾸页</a>//pageindex如果⼤于1:pageindex=3(当前页=3)则存在第1页第2页,允许点击上⼀页@if (ViewBag.pageindex > 1){<a href="javascript:;" onclick="goPage(@(ViewBag.pageindex - 1))">上⼀页</a>}else{<a href="javascript:;" class="noContent">上⼀页</a>}//如果数量⼤于当前页pageindex*15则允许点击下⼀页/末页@if (ViewBag.total > ViewBag.pageindex * 15){<a href="javascript:;" onclick="goPage(@(ViewBag.pageindex + 1))" class="noContent">下⼀页</a>//向上取整<a href="javascript:;" onclick="goPage(@(Math.Ceiling(Convert.ToDouble(ViewBag.total)/15)))" class="noContent">末页</a> }else {<a href="javascript:;" class="noContent">下⼀页</a><a href="javascript:;" class="noContent">末页</a>}</div><script type="text/javascript">goPage = (function (page) {var s = window.location.href;if (/pageindex=/.test(s))s = s.replace(/pageindex=[0-9]*/, "pageindex=" + page);elses = s + "&pageindex=" + page;if (!/\?/.test(s))s = s.replace("&", "?");window.location.href = s;});</script>。
JSP分页显⽰的实例代码select * from tablename limit startPoint, numberPerPage;tablename 就是要分页显⽰的那张表的名称;startPoint 就是起始的位置 -1;numberPerPage 就是⼀页显⽰的条数。
例如: select * from comment limit 20,5;则是从comment表中抽取21~25号评论:MySQL的limit关键字可以完成抽取⼀定范围(n,n+m]的记录,也就是说需要两个参数来决定某⼀页显⽰的内容,即“第x页”以及每页显⽰的个数。
每页显⽰的个数可以在程序中设定,也可以由⽤户设定。
但,“第x页”这个参数⼀定是⽤户给出的。
当⽤户点击页数、下⼀页/上⼀页按钮或跳转⾄某页时,需要将这个“第x页”参数传送给服务器,以便进⾏记录的抽取。
复制代码代码如下:function goToPage(page){ $('body').load("getComments.do?page=" + page);}或者,两个参数都由⽤户指定的话,函数可以写成:复制代码代码如下:function goToPage(page, numberPerPage){ $('body').load("getComments.do?page=" + page + "&npp=" + numberPerPage);}servlet通过接受jsp页⾯传来的request对象中的page和npp参数来获悉⽤户希望浏览第X页,以及⼀页显⽰多少条记录。
复制代码代码如下:int page = Integer.parseInt(req.getParameter("page"));⼀般⼀次显⽰10页左右,也就是假如现在在第52页,那么可选的页数列表就是50、51、52。