Ajax No Refresh Paging

Source: Internet
Author: User
Tags tagname


The main technical focus is the read and write operation of the XML document. Because the foreground page and background data paging are interactive using an XML document. This example will focus on how DOM technology generates XML documents.

The code is as follows:

try {
Create an XML document build factory
Documentbuilderfactory builderfactory = Documentbuilderfactory.newinstance ();
Creating an XML Document Build object
Documentbuilder Documentbuilder = Builderfactory.newdocumentbuilder ();
doc = Documentbuilder.newdocument (); Create a Document Object
} catch (Parserconfigurationexception ex) {
Logger.getlogger (AjaxFenyeService.class.getName ()). log (Level.severe, NULL, ex);
}
Element createelement (String tagName)
TagName: The name of the node.
AppendChild (Node newChild)
The implementation object of the Newchild:node interface, the element class implements the node interface, so an instance object of the element class can be used directly as a parameter to the method.
Element root = doc.createelement ("Products"); Create the root node of the XML
Doc.appendchild (root); Adding a root node to an XML document
Pageargs Pageargs = Dao.getpageargs (); Get Data Paging parameters
Pageargs.setpagecount (page); Set the current paging page number
Element Pagearg = doc.createelement ("Pagearg"); Create a paging information node
Root.appendchild (PAGEARG); Add paging information to the root node
Element pagenumelement = doc.createelement ("Pagenum");//Add current page number parameter
Pagearg.appendchild (pagenumelement);
Public Domsource (Node node)
Node: This parameter is the DOM node object, which acts as the input source.
public abstract void Transform (Source xmlsource,
Result outputtarget)
Xmlsource:dom Data source
Outputtarget: Saving the output stream of an XML document
Creating an XML Converter
Transformer tf = Transformerfactory.newinstance (). Newtransformer ();
OutputStream out = Resp.getoutputstream (); Get answer output stream
Domsource ds = new Domsource (DOC); Creating an XML data source
Streamresult stream = new Streamresult (out);
Tf.setoutputproperty (outputkeys.indent, "yes"); Indent XML Document Format
Tf.transform (DS, stream); Output data to the browser
Out.close ();

******* writes index.jsp home file, adds <label> tags to the home file, sets the label's ID property to "ProductList", which is used to save paging data. The key code is as follows:
<body onload= "requestpage (1)";
<label id= ProductList "></LABEL>
</body>

Write a JavaScript script in the page, create the Requestpage () method, which is used to create the request object, send a request to the server to get paging data, and set the data returned by the server to be handled by the Readpage () method. The key code is as follows.
<script type= "Text/javascript" >
var xmlHttp;
function Requestpage (page) {
Initialize the object and issue a XMLHttpRequest request
if (window. XMLHttpRequest) {//Mozilla or other browser other than IE
XmlHttp = new XMLHttpRequest ();
} else if (window. ActiveXObject) {//IE browser
try {
XmlHttp = new ActiveXObject ("Msxml2.xmlhttp");
} catch (e) {
try {
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xmlhttp) {
Alert ("Cannot create XMLHTTP instance!");
return false;
}
Xmlhttp.onreadystatechange = Readpage; The Readpage () method handles the server response
Xmlhttp.open ("GET", "fenyeservice?page=" +page,true); Send Request Object
Xmlhttp.send (NULL);
}

Scripting Readpage () method, the paging data returned by the server is an XML document format that parses the XML document when the server correctly returns paging data, adding the specified page data and paging parameter information to the <label> label of the page, which updates only <label> the data in the tag without reloading the entire page. The key code is as follows
function Readpage () {
if (xmlhttp.readystate==4) {
if (xmlhttp.status==200) {
var doc=xmlhttp.responsexml; Receiving an XML Document object
var pagenum = doc.getelementsbytagname ("Pagenum") [0].firstchild.data; Gets the current page number parameter
var maxpage= doc.getelementsbytagname ("MaxPage") [0].firstchild.data; Get maximum page number parameter
var prepage = doc.getelementsbytagname ("Prepage") [0].firstchild.data; Gets the page number parameter of the previous page
var nextPage = doc.getelementsbytagname ("NextPage") [0].firstchild.data; Get next Page number parameter
var products = Doc.getelementsbytagname ("Product"); Get all the paging data
var InnerHTML = ""; Define insert <label> Label data
if ((products!=null) && (products.length!=0)) {
innerhtml+= "<table border=1 width= ' >"; Insert Table header information
innerhtml+= "<tr align= ' center ' ><th>ISBN</th><th> title </th>";
innerhtml+= "<th> author </th><th> publisher </th>";
innerhtml+= "<th> Unit price </th><th> publication date </th></tr>";
for (Var i=0;i<products.length;i++) {//traverse all books of an XML document
var product = Products[i];
var ISBN = Product.childnodes[0].firstchild.data;
var bookname = Product.childnodes[1].firstchild.data;
var writer = Product.childnodes[2].firstchild.data;
var publishing = Product.childnodes[3].firstchild.data;
var price = Product.childnodes[4].firstchild.data;
var date = Product.childnodes[5].firstchild.data;
InnerHTML + = "<tr>";
InnerHTML + = "<td>" +isbn+ "</td>"; Insert the book information into the form
InnerHTML + = "<td>" +bookname+ "</td>";
InnerHTML + = "<td>" +writer+ "</td>";
InnerHTML + = "<td>" +publishing+ "</td>";
InnerHTML + = "<td>" +price+ "</td>";
InnerHTML + = "<td>" +date+ "</td>";
InnerHTML + = "</tr>";
}
innerhtml+= "<tr><td align= ' center ' colspan= ' 6 ' >"; Add a paginated hyperlink
InnerHTML + = "<a href=\" javascript:void (0) \ "onclick=\" requestpage (1) \ "> First page </a>";
InnerHTML + = "<a href=\" javascript:void (0) \ "onclick=\" Requestpage ("+prepage+") \ "> Prev </a>";
InnerHTML + = pagenum+ "/" +maxpage;
InnerHTML + = "<a href=\" javascript:void (0) \ "onclick=\" Requestpage ("+nextpage+") \ "> Next </a>";
InnerHTML + = "<a href=\" javascript:void (0) \ "onclick=\" Requestpage ("+maxpage+") \ "> Last </a>";
innerhtml+= "</td></tr>\n";
innerhtml+= "</table>\n";
}else {
InnerHTML + = "Temporarily without any data";
}
document.getElementById ("ProductList"). InnerHTML = InnerHTML;
} else {
Alert (' The page you requested was found to be wrong ');
}
}
}

Write the Ajaxfenyeservice class, which is the servlet controller that handles paging requests, which overrides the Doget () method of the servlet to handle paging requests, which first create an XML Document object. Reads the paging parameter information from the database and adds it to the root node of the XML Document object. The key code is as follows
@Override
protected void Doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
try {
Create an XML document build factory
Documentbuilderfactory builderfactory = Documentbuilderfactory.newinstance ();
Creating an XML Document Build object
Documentbuilder Documentbuilder = Builderfactory.newdocumentbuilder ();
doc = Documentbuilder.newdocument (); Create a Document Object
} catch (Parserconfigurationexception ex) {
Logger.getlogger (AjaxFenyeService.class.getName ()). log (Level.severe, NULL, ex);
}
List books = null; Create a data collection
Resp.setcontenttype ("Application/xml"); Set the reply type to XML
Gets the paging parameter of the request object
int page = Servletrequestutils.getintparameter (req, "page", 1);
Element root = doc.createelement ("Products"); Create the root node of the XML
Doc.appendchild (root); Adding a root node to an XML document
Pageargs Pageargs = Dao.getpageargs (); Get Data Paging parameters
Pageargs.setpagecount (page); Set the current paging page number
Element Pagearg = doc.createelement ("Pagearg"); Create a paging information node
Root.appendchild (PAGEARG); Add paging information to the root node
Element pagenumelement = doc.createelement ("Pagenum"); Add current page number parameter
Pagearg.appendchild (pagenumelement);
Text Pagenumvalue = Doc.createtextnode (Pageargs.getpagenum () + "");
Pagenumelement.appendchild (Pagenumvalue);
Add maximum page number parameter
Element maxpageelement = doc.createelement ("MaxPage");
Pagearg.appendchild (maxpageelement);
Text Maxpagevalue = Doc.createtextnode (pageargs.getmaxpage () + "");
Maxpageelement.appendchild (Maxpagevalue);
Add page number parameters for next page
Element nextpageelement = doc.createelement ("NextPage");
Pagearg.appendchild (nextpageelement);
Text Nextpagevalue = Doc.createtextnode (pageargs.getnextpage () + "");
Nextpageelement.appendchild (Nextpagevalue);
Add page number parameters for previous page
Element prepageelement = doc.createelement ("Prepage");
Pagearg.appendchild (prepageelement);
Text Prepagevalue = Doc.createtextnode (pageargs.getprepage () + "");
Prepageelement.appendchild (Prepagevalue);
try {//Add book node
Books = dao.getproducts (page);
for (Object pro:books) {
Fenyebean Fenyebean = (Fenyebean) Pro;
Element Product = doc.createelement ("Product");
Root.appendchild (product);
Element Isbnnode = doc.createelement ("ISBN"); Create an ISBN node
Product.appendchild (Isbnnode);
Text Isbnvalue = Doc.createtextnode (FENYEBEAN.GETISBN ());
Isbnnode.appendchild (Isbnvalue);
Element NameNode = doc.createelement ("BookName"); Create a BookName node
Product.appendchild (NameNode);
Text namevalue = Doc.createtextnode (Fenyebean.getbookname ());
Namenode.appendchild (Namevalue);
Element Writernode = doc.createelement ("Writer"); Creating a writer node
Product.appendchild (Writernode);
Text Writervalue = Doc.createtextnode (Fenyebean.getwriter ());
Writernode.appendchild (Writervalue);
Element Pbnode = doc.createelement ("publishing"); Create a publishing node
Product.appendchild (Pbnode);
Text pbvalue = Doc.createtextnode (fenyebean.getpublishing ());
Pbnode.appendchild (pbvalue);
Element Pricenode = doc.createelement ("price"); Create a price node
Product.appendchild (Pricenode);
Text Pricevalue = Doc.createtextnode (Fenyebean.getprice () + "");
Pricenode.appendchild (Pricevalue);
Element Datenode = doc.createelement ("Date"); Create a Date node
Product.appendchild (Datenode);
Text DateValue = Doc.createtextnode (Fenyebean.getdate (). toLocaleString ());
Datenode.appendchild (DateValue);
}
Creating an XML Converter
Transformer tf = Transformerfactory.newinstance (). Newtransformer ();
OutputStream out = Resp.getoutputstream (); Get answer output stream
Domsource ds = new Domsource (DOC); Creating an XML data source
Streamresult stream = new Streamresult (out);
Tf.setoutputproperty (outputkeys.indent, "yes"); Indent XML Document Format
Tf.transform (DS, stream); Output data to the browser
Out.close ();
} catch (Exception ex) {
Ex.printstacktrace ();
}
}
public class Pageargs {
private int pagenum; Current page number
private int pageSize; Page size
Private long maxPage; Max pages
private int prepage; Previous Page page number
private int nextPage; Next Page page
public void Setpagecount (int pagenum) {
This.pagenum = Pagenum;
prepage=pagenum-1<=1?1:pagenum-1; Set the page number of the previous page
Set the page number of the next page
nextpage= (int) (Pagenum + 1 >= maxPage? Maxpage:pagenum + 1);
}
...... Omit part of the code
}
Public Pageargs Getpageargs () {
Pageargs pag = null; Declaring a paging Parameter object
Statement stmt = null;
ResultSet rs = null;
Connection conn = Getconn (); Connecting to a database
try {
SQL statement that declares the total amount of data queried
String sql = "SELECT COUNT (*) from Tb_hibernatefenye";
stmt = Conn.createstatement ();
rs = stmt.executequery (SQL); Execute SQL query
if (Rs.next ()) {
int count = Rs.getint (1); Get query Results
Pag = new Pageargs (); Initializing the paging Parameter object
Pag.setpagesize (pageSize); Set Paging size
Pag.setmaxpage ((count + pageSize-1)/pageSize); Set Maximum page number
Pag.setpagecount (count); Set the current page number
}
} catch (SQLException ex) {
Logger.getlogger (GetClass (). GetName ()). log (Level.severe, NULL, ex);
} finally {
Close (RS, stmt, conn);
}
return pag;
}
Public List getproducts (final int page) throws Exception {
if (pageSize = = 0) {
throw new Exception ("Page size for product paging cannot be 0");
}
List List = new ArrayList (); Create a collection object that holds paging data
PreparedStatement stmt = null;
ResultSet rs = null;
Connection conn = Getconn (); Connecting to a database
try {
Define SQL statements for paged queries
String sql = "SELECT * from Tb_databasetoexcel limit?,?";
stmt = conn.preparestatement (sql);
Stmt.setint (1, (page-1) *pagesize); Setting SQL query Parameters
Stmt.setint (2, pageSize); Setting SQL query Parameters
rs = Stmt.executequery (); Get query Results
while (Rs.next ()) {//Traverse query result set
Fenyebean Fenyebean = new Fenyebean (); Create a Paging object
FENYEBEAN.SETISBN (Rs.getstring ("ISBN")); Initializing paging objects
Fenyebean.setbookname (rs.getstring ("BookName"));
Fenyebean.setpublishing (Rs.getstring ("Publishing"));
Fenyebean.setwriter (Rs.getstring ("writer"));
Fenyebean.setprice (Rs.getfloat ("price"));
Fenyebean.setdate (Rs.getdate ("date"));
List.add (Fenyebean); Add a paging data object to the list collection
}
} catch (SQLException ex) {
Logger.getlogger (GetClass (). GetName ()). log (Level.severe, NULL, ex);
} finally {
Close (RS, stmt, conn);
}
return list;
}

Ajax No Refresh Paging

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.