在瀏覽網(wǎng)頁時,經(jīng)常會看到分頁顯示的頁面。如果想把大量的數(shù)據(jù)提供給瀏覽者,分頁顯示是個非常實(shí)用的方法。分頁顯示數(shù)據(jù)能夠幫助瀏覽者更好地查看信息,能夠有條理的顯示信息。
在傳統(tǒng)的web技術(shù)中,分頁顯示的相關(guān)操作都是在服務(wù)器端進(jìn)行的,服務(wù)器端獲取客戶端的請求分頁,并根據(jù)請求頁數(shù)獲取指定的結(jié)果集。最后把結(jié)果集中的數(shù)據(jù)返回到客戶端,這時返回結(jié)果中不但包含了數(shù)據(jù),還可能包含了數(shù)據(jù)的顯示樣式??蛻舳说拿恳淮螖?shù)據(jù)更新,都會重新打開一個網(wǎng)頁,如果網(wǎng)頁中包含了很多html元素,就會造成網(wǎng)頁打開速度較慢的情況。
為了顯示部分?jǐn)?shù)據(jù),而需要加載整個頁面的數(shù)據(jù),顯得有點(diǎn)得不償失。使用Ajax技術(shù)可以很好的彌補(bǔ)這些問題,服務(wù)器端只傳輸數(shù)據(jù)庫表中的數(shù)據(jù),客戶端獲取這些數(shù)據(jù)只更新局部內(nèi)容,與數(shù)據(jù)無關(guān)的其他元素保持不變。
現(xiàn)在創(chuàng)建一個實(shí)例,以演示使用Ajax技術(shù)實(shí)現(xiàn)數(shù)據(jù)的分頁顯示。該實(shí)例的代碼實(shí)現(xiàn)分為服務(wù)器端和客戶端。
1,準(zhǔn)備工作
我們這里使用Mysql數(shù)據(jù)庫,我在shop數(shù)據(jù)庫中創(chuàng)建了一張mobileshop表,這張表有兩個字段name,model。
打開記事本,輸入下列代碼:
<%
class DBManager{
String userName="root";
String password="123456";
Connection conn=null;
Statement stmt=null;
String url="jdbc:mysql://localhost:3306/shop";
ResultSet rst;
public DBManager(String sql){
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,userName,password);
stmt=conn.createStatement();
rst=stmt.executeQuery(sql);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ResultSet getResultSet(){
return rst;
}
}
%>
將上述代碼保存為Conn.jsp,用于返回查詢結(jié)果集。
2,服務(wù)器端代碼
在本實(shí)例中,服務(wù)器端代碼具有獲取客戶端請求頁數(shù)和產(chǎn)生指定記錄集的功能。打開記事本,輸入下列代碼:
<%@ include file="Conn.jsp" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%
try
{
ResultSet rs=new DBManager("select name,model from mobileshop").getResultSet();
int intPageSize; //一頁顯示的記錄數(shù)
int intRowCount; //記錄的總數(shù)
int intPageCount; //總頁數(shù)
int intPage; //待顯示的頁碼
String strPage;
int i;
intPageSize=2; //設(shè)置一頁顯示的記錄數(shù)
strPage=request.getParameter("page"); //取得待顯示的頁碼
if(strPage==null) //判斷strPage是否等于null,如果是,則顯示第一頁數(shù)據(jù)
{
intPage=1;
}else{
intPage=java.lang.Integer.parseInt(strPage); //將字符串轉(zhuǎn)化為整形
}
if(intPage<1)
{
intPage=1;
}
//獲取記錄總數(shù)
rs.last();
intRowCount=rs.getRow();
//計算總頁數(shù)
intPageCount=(intRowCount+intPageSize-1)/intPageSize;
//調(diào)整顯示的頁碼
if(intPage>intPageCount) intPage=intPageCount;
if(intPageCount>0)
{
//將記錄指針定位到待顯示頁的第一條記錄上
rs.absolute((intPage-1)*intPageSize+1);
}
//下面用于顯示數(shù)據(jù)
i=0;
StringBuffer content=new StringBuffer("");
response.setContentType("text/xml");
response.setHeader("Cache-Control","no-cache");
content.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
content.append("<contents>");
while(i<intPageSize && !rs.isAfterLast())
{
String name=rs.getString("name");
String email=rs.getString("model");
content.append("<content>");
content.append("<name>"+ name +"</name>");
content.append("<model>"+email+"</model>");
content.append("</content>");
rs.next();
i++;
}
content.append("</contents>");
System.out.print(content);
out.print(content);
}
catch(Exception e)
{
e.printStackTrace();
}
%>