Files: Xmlservlet.java
Package servlet;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import javax.servlet.ServletException;
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 Javax.xml.transform.OutputKeys;
Import javax.xml.transform.*;
Import javax.xml.transform.dom.*;
Import org.w3c.dom.Document;
Import org.w3c.dom.Element;
public class Xmlservlet extends HttpServlet {
public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
This.dopost (request, response);
}
public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
String content_type = "text/xml; charset=gb2312 ";
Response.setcontenttype (Content_Type);
PrintWriter out = Response.getwriter ();
StringBuffer sb = new StringBuffer ("<address>");
Sb.append ("<type_name>AAhl</type_name>");
Sb.append ("<type_name>BB</type_name>");
Sb.append ("<type_name>CC</type_name>");
Sb.append ("<type_name>DD</type_name>");
Sb.append ("</address>");
Out.write (Sb.tostring ());
Out.close ();
}
}
///////////////////////////
Read the myajax.jsp of the XML file sent by Xmlservlet.java
<%@ page language= "java" import= "java.util.*" pageencoding= "GBK"%>
<script language= "JavaScript" >
var xmlHttp;
function Createxmlhttp () {
if (window. XMLHttpRequest) {
XmlHttp = new XMLHttpRequest ();
}else{
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
}
}
It's all here to get the XMLHttpRequest object.
function GetInfo () {
Createxmlhttp ();
Xmlhttp.open ("POST", "Servlet/xmlservlet"); Establish a data request to the server, where a file called "Allarea.xml" is requested
Xmlhttp.onreadystatechange = Getcitycallback; A callback function
Xmlhttp.send (NULL); Data that you want the server to send
}
function Getcitycallback () {
if (xmlhttp.readystate = = 4) {
if (Xmlhttp.status = = 200) {//The two if statements here are to determine whether the request has been completed
var allareahlp = Xmlhttp.responsetext;
alert (Allareahlp);
var type = XmlHttp.responseXML.getElementsByTagName ("type_name");
Alert ("---------");
var str=new Array ();
for (Var i=0;i<type.length;i++) {
Str[i]=type[i].firstchild.data;
Alert (Str[i]);
document.all[' TD '].innerhtml+=str[i]+ <BR> ';
}
}
}
}
</script>
<body onload = "GetInfo ()" >
<table width= "80%" border= "0" cellspacing= "0" cellpadding= "0" >
<tr>
<TD id= "TD" >
</td>
</tr>
</table>
</body>
The key is to generate the XML file data in the servlet