Java中实现分页效果的详细代码

Java中实现分页效果的详细代码,第1张

<head>

<%

const MaxPerPage=20

dim sql

dim rs

dim totalPut

dim CurrentPage

dim TotalPages

dim i,j

%>

</head>

<body>

<%

conn = "DBQ=" + servermappath("wj028mdb") + ";DefaultDir=;DRIVER={Microsoft Access Driver (mdb)};"

sql = "SELECT FROM USER order by id desc"

set rs=servercreateobject("adodbrecordset")

rsopen SQL,conn,1,1

rsMoveFirst

rspagesize=MaxPerPage

howmanyfields=rsFieldsCount-1

If trim(Request("Page"))<>"" then

CurrentPage= CLng(request("Page"))

If CurrentPage> rsPageCount then

CurrentPage = rsPageCount

End If

Else

CurrentPage= 1

End If

if rseof then

responsewrite "<p align='center'>没有记录!</p>"

else

totalPut=rsrecordcount

if CurrentPage<>1 then

if (currentPage-1)MaxPerPage<totalPut then

rsmove(currentPage-1)MaxPerPage

dim bookmark

bookmark=rsbookmark

end if

end if

dim n,k

if (totalPut mod MaxPerPage)=0 then

n= totalPut \ MaxPerPage

else

n= totalPut \ MaxPerPage + 1

end if%>

<% i=0

do while not rsEOF and i<maxperpage

%>

<%

rsmovenext

i=i+1

loop

%>

第<%=currentpage%>页

共<%=n%>页

<%

k=currentpage

if k<>1 then

responsewrite "[<b>"+"<a href='listasppage=1'>首页</a></b>]"

responsewrite "[<b>"+"<a href='listasppage="+cstr(k-1)+"'>上一页</a></b>]"

else

ResponseWrite "[首页][上一页]"

end if

if k<>n then

responsewrite "[<b>"+"<a href='listasppage="+cstr(k+1)+"'>下一页</a></b>] "

responsewrite "[<b>"+"<a href='listasppage="+cstr(n)+"'>尾页</a></b>] "

else

ResponseWrite "[下一页][尾页]"

end if

%>

<%

end if

set rs=nothing

set conn=nothing

%>

</body>

/

  分页代码

  

  @author Star

  @version 10 2008/07/08

 /

public class CutPage implements Serializable{

private static Log log = LogFactorygetLog(CutPageclass);

private int curPageNo = 0; // 当前页数,从0开始

private int size = 0; // 所有数据条数

private String url; // 页面跳转的路径

private List showList; // 当前页面需要显示的数据列表

private int pageSize = 20;// 每页显示的数据条数

private int groupSize = 1;// 多少页为一组

private String pageNavigation;// 导航条

/

  每次通过sql语句从数据库里面分组取出需要显示的数据

  

  @param request

             javaxservlet> }

太多了,贴不下,见附件

//============分页功能===============

int pageSize=3; //一页显示几条记录

int pageNow=1; //希望显示第几条记录

//动态的接收pageNow

String sPageNow=reqgetParameter("pageNowok");

if(sPageNow!=null){

pageNow=IntegerparseInt(sPageNow);

}

//调用UserBeanC1

UserBeanC1 ubc = new UserBeanC1();

ArrayList al =ubcgetResultByPage(pageNow,pageSize);

pwprintln("<table border=2>");

pwprintln("<tr><th>id</th><th>name</th><th>passwd</th><th>mail</th><th>grade</th><th>修改用户</th><th>删除用户</th></tr>");

for(int i=0;i<alsize();i++){

UserBean ub = (UserBean)alget(i);

pwprintln("<tr>");

pwprintln("<td>"+ubgetUserId()+"</td>");

pwprintln("<td>"+ubgetUserName()+"</td>");

pwprintln("<td>"+ubgetPasswd()+"</td>");

pwprintln("<td>"+ubgetMail()+"</td>");

pwprintln("<td>"+ubgetGrade()+"</td>");

pwprintln("<td><a href=>修改</a></td>");

pwprintln("<td><a href=delUserC1userId="+ubgetUserId()+" onclick=\"return windowconfirm('确认删除吗')\">删除</a></td>");

pwprintln("</tr>");

}

pwprintln("</table>");

//上一页

if(pageNow!=1){

pwprintln("<a href=welpageNowok="+(pageNow-1)+">上一页</a>");

}

//显示超链接

for(int i=pageNow;i<=pageNow+pageSize+1;i++){

pwprintln("<a href=welpageNowok="+i+">"+i+"</a>");

}

int pageCount=ubcgetPageCount();

//下一页

if(pageNow!=pageCount-4){

pwprintln("<a href=welpageNowok="+(pageNow+1)+">下一页</a><br>");

}

pwprintln("<br>该网页被访问了"+thisgetServletContext()getAttribute("visitTimes")toString()+"次<br>");

pwprintln("您的IP地址是:"+reqgetRemoteAddr()+"<br>");

pwprintln("您的机器名是:"+reqgetRemoteHost()+"<br>");

pwprintln("</center><hr><img src=imgs/1gif><br>");

pwprintln("</body>");

hibernate

有分页的查询函数可用

搜索后分页:

在页面中使用隐藏域,

搜索之后,返回的页面中隐藏域保存了搜索的信息,

而分页的链接-》执行函数将

隐藏域中的搜索信息

+

页码

作为参数传递至后台,由后台进行查询~~

往后台传字符串乱码问题?

你的页面是什么编码?执行请求是get

还是post方法,get方法的话需要注意url中包含中文字符的问题,可以先将其转为iso8859-1再发送请求。

在后台获取到中文信息出现乱码的话,可以使用一个全局的过滤器,将

请求中的编码信息设置为页面所用的编码,此后再获取信息时,控制器将自动进行编码转换了(如iso8859-1

到gbk的转换)。

强烈建议数据库、程序、页面都使用utf8的编码!

如果不用隐藏域的话,用cookie去控制~~

//分页类

public class Pager {

private int pageNow = 1;//

private int pageSize = 7;//

private int totalPage;//

private int totalSize;//

public Pager(int pageNow, int totalSize) {

thispageNow = pageNow;

thistotalSize = totalSize;

}

public int getPageNow() {

return pageNow;

}

public void setPageNow(int pageNow) {

thispageNow = pageNow;

}

public int getPageSize() {

return pageSize;

}

public void setPageSize(int pageSize) {

thispageSize = pageSize;

}

public int getTotalPage() {

totalPage = getTotalSize() / getPageSize();

if (totalSize % pageSize != 0)

totalPage++;

return totalPage;

}

public void setTotalPage(int totalPage) {

thistotalPage = totalPage;

}

public int getTotalSize() {

return totalSize;

}

public void setTotalSize(int totalSize) {

thistotalSize = totalSize;

}

public boolean isHasFirst() {

if (pageNow == 1)

return false;

else

return true;

}

public void setHasFirst(boolean hasFirst) {

}

public boolean isHasPre() {

if (thisisHasFirst())

return true;

else

return false;

}

public void setHasPre(boolean hasPre) {

}

public boolean isHasNext() {

if (isHasLast())

return true;

else

return false;

}

public void setHasNext(boolean hasNext) {

}

public boolean isHasLast() {

if (pageNow == thisgetTotalPage())

return false;

else

return true;

}

public void setHasLast(boolean hasLast) {

}

}

//service层

public class PageService {

@SuppressWarnings("unchecked")

public List<> list(int pageNow, int pageSize, String hql) {

Session session = HibernateSessionFactorygetSession();

Transaction tx = sessionbeginTransaction();

List<Object> objects;

Query query = sessioncreateQuery(hql);

querysetFirstResult(pageSize  (pageNow - 1));

querysetMaxResults(pageSize);

objects = querylist();

txcommit();

return objects;

}

}

//在action中调用public String listUser() {

String hql = "from Userinfo u";

if (pslist(pageNow, pageSize, hql) != null) {

userinfos = (List<Userinfo>) pslist(pageNow, pageSize, hql);

Map<String, Object> request = (Map<String, Object>) ActionContext

getContext()get("request");

Pager page = new Pager(thisgetPageNow(), usgetUserSize());

requestput("userinfos", userinfos);

requestput("page", page);

return ActionSUCCESS;

} else {

return ActionLOGIN;

}

}

//jsp中

<body>

<table width="832" border="0" cellpadding="0" cellspacing="0" id="listBook">

  <tr bgcolor="#E7E7E9">

    <td width="5%" height="40">&nbsp;</td>

    <td width="25%" colspan="2" bgcolor="#E7E7E9"><div align="center" class="STYLE10">邮箱</div></td>

    <td width="25%" colspan="2" bgcolor="#E7E7E9" class="STYLE1"><div align="center" class="STYLE10">密码</div></td>

    <td width="25%" colspan="2" bgcolor="#E7E7E9" class="STYLE1"><div align="center" class="STYLE10">权限</div></td>

    <td width="8%" bgcolor="#E7E7E9"><span class="STYLE8"></span></td>

    <td width="8%" bgcolor="#E7E7E9"><span class="STYLE8"></span></td>

  </tr>

  <s:iterator value="#requestuserinfos" id="oneUser">

  <tr>

    <td height="50">

    

      <div align="center">

        <input type="checkbox" name="checkbox" value="checkbox" />

       

    </div></td>

    <td width="5%"></td>

    <td width="23%" class="STYLE4"><s:property

value="#oneUseremail" /></td>

    <td width="5%" class="STYLE4"></td>

    <td width="23%"><span class="STYLE4"><s:property

value="#oneUserpassword" /></span></td>

    <td width="5%" class="STYLE4"></td>

    <td width="23%"><span class="STYLE4">

    <s:if test="#oneUserpower==1">

         普通用户

    </s:if>

    <s:else>

         管理员

    </s:else>

   </span></td>

    <td><div align="right" class="STYLE1"><a href='deleteUseruserid=<s:property value="#oneUserid"/>' class="STYLE5">删除|</a></div></td>

    <td class="STYLE1"><a href='lookUseruserid=<s:property value="#oneUserid"/>&pageNow=<s:property value="#requestpagepageNow"/>' target="_self" class="STYLE5">修改</a></td>

  </tr>

  </s:iterator>

  

  <tr>

    <td colspan="9"><table width="832" border="0" cellspacing="0" bgcolor="#E7E7E9">

      <s:set name="page" value="#requestpage"></s:set>

    

      <tr>

        <td width="70%">&nbsp;</td>

        <s:if test="#pageisHasPre()">

        <td width="10%"><a href='listUserpageNow=<s:property value="#pagepageNow-1"/>' target="_self" class="STYLE3" >上一页</a></td>

        </s:if>

        <s:else>

         <td width="10%"><a href="listUserpageNow=1" target="_self" class="STYLE3" >上一页</a></td>

        </s:else>

       <s:if test="#pageisHasNext()">

        <td width="10%"><a href="listUserpageNow=<s:property value="#pagepageNow+1"/>" target="_self" class="STYLE3">下一页</a></td>

        </s:if>

       <s:else>

        <td width="10%"><a href="listUserpageNow=<s:property value="#pagetotalPage"/>" target="_self" class="STYLE3">下一页</a></td>

        </s:else>

        <td width="10%"><a href="listUserpageNow=<s:property value="#pagetotalPage"/>" target="_self" class="STYLE3">尾页</a></td>

      </tr>

    </table></td>

  </tr>

</table>

</body>

</html>

这是采用struts2+hibernate 做的,你可以参考一下

package dlwsxxbase;

public class Pager {

private int totalRows; // 总行数

private int pageSize; // 每页显示的行数

private int currentPage; // 当前页号

private int totalPages; // 总页数

private int startRow; // 当前页在数据库中的起始行

private int pageStartRow; // 当前页开始行

private int pageEndRow; // 当前页结束行

private int hasNextPage; // 下一页存在标识[0:不存在,1:存在]

private int hasPreviousPage; // 前一页存在标识[0:不存在,1:存在]

public Pager() {

}

public Pager(int _totalRows,int _pageSize) {

pageSize = _pageSize;

totalRows = _totalRows;

totalPages = totalRows / pageSize;

int mod = totalRows % pageSize;

if (mod > 0) {

totalPages++;

}

currentPage = 1;

startRow = 0;

}

public int getStartRow() {

return startRow;

}

public int getpageStartRow() {

return pageStartRow;

}

public int getpageEndRow() {

return pageEndRow;

}

public int getTotalPages() {

return totalPages;

}

public int getCurrentPage() {

return currentPage;

}

public int getPageSize() {

return pageSize;

}

public int getHasNextPage() {

return hasNextPage;

}

public int getHasPreviousPage() {

return hasPreviousPage;

}

public void setTotalRows(int totalRows) {

thistotalRows = totalRows;

}

public void setStartRow(int startRow) {

thisstartRow = startRow;

}

public void setPageStartRow(int pageStartRow) {

thispageStartRow = pageStartRow;

}

public void setPageEndRow(int pageEndRow) {

thispageEndRow = pageEndRow;

}

public void setTotalPages(int totalPages) {

thistotalPages = totalPages;

}

public void setCurrentPage(int currentPage) {

thiscurrentPage = currentPage;

}

public void setPageSize(int pageSize) {

thispageSize = pageSize;

}

public void setHasNextPage(int hasNextPage) {

thishasNextPage = hasNextPage;

}

public void setHasPreviousPage(int hasPreviousPage) {

thishasPreviousPage = hasPreviousPage;

}

public int getTotalRows() {

return totalRows;

}

public void first() {

currentPage = 1;

startRow = 0;

pageStartRow = startRow + 1;

thishasFlagSet(currentPage, totalPages);

if (thishasNextPage == 0) {

pageEndRow = totalRows;

} else {

pageEndRow = startRow + pageSize;

}

}

public void previous() {

if (currentPage == 1) {

return;

}

currentPage--;

startRow = (currentPage - 1) pageSize;

pageStartRow = startRow + 1;

thishasFlagSet(currentPage, totalPages);

if (thishasNextPage == 0) {

pageEndRow = totalRows;

} else {

pageEndRow = startRow + pageSize;

}

}

public void next() {

if (currentPage < totalPages) {

currentPage++;

}

startRow = (currentPage - 1) pageSize;

pageStartRow = startRow + 1;

thishasFlagSet(currentPage, totalPages);

if (thishasNextPage == 0) {

pageEndRow = totalRows;

} else {

pageEndRow = startRow + pageSize;

}

}

public void last() {

currentPage = totalPages;

startRow = (currentPage - 1) pageSize;

pageStartRow = startRow + 1;

thishasFlagSet(currentPage, totalPages);

if (thishasNextPage == 0) {

pageEndRow = totalRows;

} else {

pageEndRow = startRow + pageSize;

}

}

public void refresh(int _currentPage) {

currentPage = _currentPage;

if (currentPage > totalPages) {

last();

}

thishasFlagSet(currentPage, totalPages);

}

private void hasFlagSet(int currentPage, int totalPages) {

if (currentPage == totalPages) {

if (currentPage == 1) {

thishasPreviousPage = 0;

thishasNextPage = 0;

} else {

thishasPreviousPage = 1;

thishasNextPage = 0;

}

} else {

if (currentPage == 1) {

thishasPreviousPage = 0;

thishasNextPage = 1;

} else {

thishasPreviousPage = 1;

thishasNextPage = 1;

}

}

}

}

这是我的工程里的分页核心代码,希望对你有用,还有ssh分页文档,可以参照研究一下。

使用分页类,直接调用就可以,代码如下:

package comgodwinnewsutil;

import javaioUnsupportedEncodingException;

import javanetURLDecoder;

import javautilArrayList;

/

分页类,用于封闭分页显示信息

@author javabs

/

public class Pager {

// 当前页

private int currentPage;

// 总页数

private int totalPage;

// 总记录数

private int totalRecord;

// 每页条数

private int pageSize;

// 是否有下一页

private int hasNext;

private ArrayList keys;

private ArrayList values;

// 查询串

private String queryString;

// 首页

private String firstLink;

// 上一页

private String previousLink;

// 下一页

private String nextLink;

// 尾页

private String lastLink;

// 链接

private String forScriptLink;

public Pager(int pageSize, String queryString) {

keys = new ArrayList();

values = new ArrayList();

setQueryString(queryString);

setPageSize(pageSize);

}

public String getForScriptLink() {

if (keyscontains("toPage"))

removeKey("toPage");

String tmp = getQueryString();

if (tmplength() == 0)

return "";

else

return "" + tmp + "&";

}

public int getCurrentPage() {

return currentPage;

}

public void setCurrentPage(String toPage) {

int tmpage = 1;

try {

tmpage = IntegerparseInt(toPage);

} catch (NumberFormatException e) {

tmpage = 1;

}

if (tmpage < 1)

tmpage = 1;

else if (tmpage > getTotalPage())

tmpage = getTotalPage();

currentPage = tmpage;

}

public String getFirstLink() {

return getQueryStr(1);

}

public int getHasNext() {

int i = 1;

if (getCurrentPage() >= getTotalPage())

i = 0;

return i;

}

public String getLastLink() {

return getQueryStr(getTotalPage());

}

public String getNextLink() {

return getQueryStr(currentPage == totalPage currentPage : (currentPage + 1));

}

public int getPageSize() {

return pageSize;

}

public void setPageSize(int pageSize) {

thispageSize = pageSize;

}

public String getPreviousLink() {

return getQueryStr(currentPage == 1 currentPage : currentPage - 1);

}

public void setPreviousLink(String previousLink) {

thispreviousLink = previousLink;

}

public String getQueryString() {

StringBuffer sb = new StringBuffer();

for (int i = 0; i < keyssize(); i++) {

String key = (String) keysget(i);

String value = (String) valuesget(i);

sbappend("&");

sbappend(key);

sbappend("=");

sbappend(value);

}

return sbdelete(0, 1)toString();

}

public void setQueryString(String queryString) {

if (queryString != null) {

String s[] = queryStringsplit("&");

for (int i = 0; i < slength; i++) {

String s1[] = s[i]split("=");

if (s1length == 2) {

keysadd(s1[0]);

valuesadd(s1[1]);

} else {

keysadd(s1[0]);

valuesadd("");

}

}

}

}

public int getTotalPage() {

return totalPage;

}

public void setTotalPage() {

if (totalRecord % pageSize == 0) {

totalPage = totalRecord / pageSize;

totalPage = totalPage == 0 1 : totalPage;

}

else

totalPage = totalRecord / pageSize + 1;

}

public int getTotalRecord() {

return totalRecord;

}

public void setTotalRecord(int totalRecord) {

thistotalRecord = totalRecord;

setTotalPage();

}

public String[] getQueryParameterValues(String key) {

return getQueryParameterValues(key, "UTF-8");

}

public String[] getQueryParameterValues(String key, String decode) {

ArrayList ret = new ArrayList();

for (int i = 0; i < keyssize(); i++)

if (((String) keysget(i))equals(key))

try {

retadd(URLDecoderdecode((String) valuesget(i), decode));

} catch (UnsupportedEncodingException e) {

retadd((String) valuesget(i));

}

if (retsize() == 0)

return null;

String strArr[] = new String[retsize()];

for (int i = 0; i < retsize(); i++)

strArr[i] = (String) retget(i);

return strArr;

}

public String getQueryParameter(String key) {

return getQueryParameter(key, "UTF-8");

}

public String getQueryParameter(String key, String decode) {

String value = "";

if (key != "toPage") {

try {

value = URLDecoderdecode(getValue(key), decode);

} catch (UnsupportedEncodingException e) {

value = getValue(key);

}

} else {

int tmpage = 1;

try {

value = getValue(key);

tmpage = IntegerparseInt(value);

} catch (NumberFormatException e) {

tmpage = 1;

} catch (NullPointerException e1) {

tmpage = 1;

}

if (tmpage < 1)

tmpage = 1;

else if (tmpage > getTotalPage())

tmpage = getTotalPage();

value = (new StringBuffer(StringvalueOf(tmpage)))toString();

}

return value;

}

public void setQueryParameter(String key, String value) {

if (keyequals("toPage"))

removeKey(key);

keysadd(key);

valuesadd(value);

}

public String getQueryStr(int toPage) {

setQueryParameter("toPage", (new StringBuffer(StringvalueOf(toPage)))toString());

return "" + getQueryString();

}

private String getValue(String key) {

String ret = "";

for (int i = 0; i < keyssize(); i++) {

if (!((String) keysget(i))equals(key))

continue;

ret = (String) valuesget(i);

break;

}

return ret;

}

private void removeKey(String key) {

for (int i = 0; i < keyssize(); i++) {

if (!((String) keysget(i))equals(key))

continue;

keysremove(i);

valuesremove(i);

break;

}

}

public static void main(String args[]) {

String str = "a=中文aa&b=2&c=3&c=4&c=5";

Pager page = new Pager(2, str);

pagesetTotalRecord(10);

pagesetCurrentPage("1");

Systemoutprintln(pagegetFirstLink());

Systemoutprintln(pagegetPreviousLink());

Systemoutprintln(pagegetNextLink());

Systemoutprintln(pagegetLastLink());

String s = pagegetQueryParameter("a");

Systemoutprintln("s: " + s);

}

}

这里有一个,当时我用Hibernate做的,如果有啥不明白的,继续留言

index是偏移,具体可以这样计算:(当前页数 - 1)每页显示的条数

count是你每页要显示多少条

你用的时候,直接把T换成是你需要查找的类,就可以啦

public List<T> getAll(int index, int count) {

final String hql = "from T where条件";

final int offset = index;

final int length = count;

List<T> list = getHibernateTemplate()executeFind(new HibernateCallback() {

public Object doInHibernate(Session session)

throws HibernateException {

Query query = sessioncreateQuery(hql);

querysetFirstResult(offset);

querysetMaxResults(length);

List list = querylist();

return list;

}

});

return list;

}

以上就是关于Java中实现分页效果的详细代码全部的内容,包括:Java中实现分页效果的详细代码、java中如何实现百度中的分页、java代码如何实现分页功能!!!!请高手帮忙...等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zz/9736314.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-01
下一篇 2023-05-01

发表评论

登录后才能评论

评论列表(0条)

保存