Ajax uses XML examples in requests and responses

Source: Internet
Author: User

This article aims to show how to use xml for requests and corresponding data transmission, so there is no complicated xml parsing syntax, and how to parse and construct XML is not the focus of this Article; in addition, the program does not handle Chinese content. I will explain the problem of Chinese garbled characters in the following articles.
 
The program is simple:
Enter the form --> construct xml data on the client, send a request to the server --> obtain the request data on the server, parse and construct xml data, and send a response --> obtain the response data from the client, parse and display the data
 
The Code is as follows:
Xmldemo. jsp
Jsp code
<% @ Page language = "java" contentType = "text/html; charset = UTF-8"
PageEncoding = "UTF-8" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> Ajax with XML </title>
<Script type = "text/javascript" src = "js/xmldemo. js"> </script>
</Head>
<Body>
<Table align = "center">
<Tr>
<Td> Name </td>
<Td> <input type = "text" name = "name" id = "name"/> </td>
</Tr>
<Tr>
<Td> City </td>
<Td> <input type = "text" name = "city" id = "city"/> </td>
</Tr>
<Tr>
<Td colspan = "2"> <input type = "button" value = "Submit" onclick = "callServer ()"/> </td>
</Tr>
</Table>
</Body>
</Html>
Because Ajax is used for asynchronous communication, no form is required.
 
Xmldemo. js
Jsp code
// XMLHttpRequest object definition
Var xmlHttp = false;
 
Function createXmlHttpRequest (){
Try {
XmlHttp = new ActiveXObject ("Msxml2.XMLHTTP ");
} Catch (e ){
Try {
XmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ");
} Catch (e2 ){
XmlHttp = false;
}
}

If (! XmlHttp & typeof XMLHttpRequest! = "Undefined "){
XmlHttp = new XMLHttpRequest ();
}
}
 
Function callServer (){
// Obtain form data
Var name = document. getElementById ("name"). value;
Var city = document. getElementById ("city"). value;
// Construct xml format data
Var xmlString = "<profile>" +
"<Name>" + name + "</name>" +
"<City>" + city + "</city>" +
"</Profile> ";

// Obtain the XMLHttpRequest object
CreateXmlHttpRequest ();
// XmlDemo corresponds to the server servlet
XmlHttp. open ("POST", "xmlDemo", true );
// Indicates that the request content is in xml format.
XmlHttp. setRequestHeader ("Content-type", "text/xml ");
// Specify the callback function
XmlHttp. onreadystatechange = updatePage;
// Set the sent content
XmlHttp. send (xmlString );
}
 
// Callback Function Definition
Function updatePage (){
If (xmlHttp. readyState = 4 ){
If (xmlHttp. status = 200 ){
// Obtain response data
XmlDoc = xmlHttp. responseXML;
Var nameElement = xmlDoc. getElementsByTagName ("name"). item (0 );
Var name = nameElement. firstChild. nodeValue;
Var cityElement = xmlDoc. getElementsByTagName ("city"). item (0 );
Var city = cityElement. firstChild. nodeValue;

Alert ("Name:" + name + "\ n" + "City:" + city );
} Else {
Alert ("Error: status code is" + xmlHttp. status );
}
}
}
 
XmlDemoServlet. java
Java code
Package com. ajaxdemo. servlet;
 
Import java. io. IOException;
Import java. io. PrintWriter;
 
Import javax. servlet. ServletException;
Import javax. servlet. annotation. WebServlet;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Import javax. xml. parsers. DocumentBuilder;
Import javax. xml. parsers. DocumentBuilderFactory;
Import javax. xml. parsers. ParserConfigurationException;
 
Import org. w3c. dom. Document;
Import org. w3c. dom. Node;
Import org. xml. sax. SAXException;
 
Import com.sun.org. apache. xerces. internal. jaxp. DocumentBuilderFactoryImpl;
 
/**
* Servlet implementation class XmlDemoServlet
*/
@ WebServlet ("/xmlDemo ")
Public class XmlDemoServlet extends HttpServlet {
Private static final long serialVersionUID = 1L;

/**
* @ See HttpServlet # HttpServlet ()
*/
Public XmlDemoServlet (){
Super ();
}
 
/**
* @ See HttpServlet # doPost (HttpServletRequest request, HttpServletResponse response)
*/
Protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ProcessRequest (request, response );
}
 
Private void processRequest (HttpServletRequest req, HttpServletResponse res) throws IOException {
// Document Object
Document doc = null;
DocumentBuilderFactory dbf = new DocumentBuilderFactoryImpl ();
Try {
DocumentBuilder db = dbf. newDocumentBuilder ();
Doc = db. parse (req. getInputStream ());
} Catch (ParserConfigurationException e ){
E. printStackTrace ();
} Catch (SAXException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
}

// Obtain Request Parameters
Node nameElement = doc. getElementsByTagName ("name"). item (0 );
String name = nameElement. getFirstChild (). getNodeValue ();
Node cityElement = doc. getElementsByTagName ("city"). item (0 );
String city = cityElement. getFirstChild (). getNodeValue ();

// System. out. println ("#" + name + "" + city + "#");

// Construct response xml format data
String xmlData = "<profile>" +
"<Name>" + name + "</name>" +
"<City>" + city + "</city>" +
"</Profile> ";

// Set the response format
Res. setContentType ("text/xml ");
PrintWriter out = res. getWriter ();
Out. println (xmlData );

Out. close ();
}
}
The xml file is not provided here, because the servlet is registered using annotations, as shown below:
Java code
@ WebServlet ("/xmlDemo ")
 
A simple program is not perfect yet, but it should be enough to understand how to use xml format to transmit data in requests and responses.

Author "lazydoggy"
 

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.