在页面中,用javascript产生xml文件,传递给后台的servlet,servlet处理完毕后返回给页面中的javascript,javascript再将其结果在页面中显示出来。
1.index.html页面
<html>
<head>
<title>Index.html</title>
</head>
<script type="text/javascript">
var XMLHttpReq = false;
// 创建 XMLHttpRequest 对象(主函数不需改变)
function createXMLHttpRequest()
{
if (window.XMLHttpRequest)
{ // Mozilla 浏览器
XMLHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{ // IE 浏览器
try
{
XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
}
//发送请求函数(提交xml格式的请求参数)
function sendRequest(url, xml)
{
createXMLHttpRequest();
XMLHttpReq.open("POST", url, true);
XMLHttpReq.onreadystatechange = processResponse;//指定响应函数
XMLHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
XMLHttpReq.send(xml);//发送请求
/*上面四行可以直接用XMLHttpReq.open("POST",url?param=value¶m2=value2,true);
XMLHttpReq.send(null)*/
}
//创建XML
function createXML()
{
var xml = "<user>";
xml = xml + "<name>luozhaohang<\/name>";
xml = xml + "<password>100000<\/password>";
xml = xml + "<\/user>";
return xml;
}
//处理返回信息函数(处理xml格式的返回信息)
function processResponse()
{
if (XMLHttpReq.readyState == 4)
{ // 判断对象状态
if (XMLHttpReq.status == 200)
{ // 信息已经成功返回,开始处理信息
readXml();
}
else
{ //页面不正常
window.alert("您所请求的页面有异常。");
}
}
}
function readXml()
{
var objects = XMLHttpReq.responseXML.getElementsByTagName("user");
for ( var i = 0; i < objects.length; i++)
{
var object = objects[i];
var name = object.getElementsByTagName("sname")[0].firstChild.data;
var password = object.getElementsByTagName("spassword")[0].firstChild.data;
alert("Name:" + name + ",Password:" + password);
}
}
function sendto()
{
var url = "/Luo/servlet/TestServlet";
var xml = createXML();
sendRequest(url, xml);
}
</script>
<body>
<input type="button" οnclick="sendto()" name="s_b" value="Ajax Test">
</body>
</html>
2.TestServlet.java
package luo;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
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.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class TestServlet extends HttpServlet
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Constructor of the object.
*/
public TestServlet()
{
super();
}
public void destroy()
{
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
request.setCharacterEncoding("UTF-8");
System.out.println("Ajax Start......");
String name = "no";
String password = "00";
/**
* 读取xml格式的参数
*/
StringBuffer readXml = new StringBuffer();
String line = null;
boolean is = false;
try
{
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
{
readXml.append(line);
is = true;
}
}
catch (Exception e)
{
System.out.println(e.toString());
}
if (is)
{
String xml = readXml.toString();
/*-------------------*/
Document xmlDoc = null;
try
{
xmlDoc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(new ByteArrayInputStream(xml.getBytes()));
}
catch (ParserConfigurationException e)
{
System.out.println("ParserConfigurationException");
}
catch (SAXException e)
{
System.out.println("SAXException");
}
catch (Exception e)
{
System.out.println(e.toString());
}
System.out.println("......已读取xml格式的参数");
/**
* 参数1
*/
name = xmlDoc.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
password = xmlDoc.getElementsByTagName("password").item(0).getFirstChild().getNodeValue();
System.out.println("Name:" + name + ",Password:" + password);
}
/**
* 返回xml格式的信息
*/
/**
* 设置输出信息的格式及字符集
*/
response.setContentType("text/xml;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
StringBuffer results = new StringBuffer(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>");
results.append("<users>");
results.append("<user>");
results.append("<sname>");
results.append(name);
results.append("</sname>");
results.append("<spassword>");
results.append(password);
results.append("</spassword>");
results.append("</user>");
results.append("</users>");
out.write(results.toString());
out.flush();/*可不要*/
out.close();
}
public void init() throws ServletException
{
// Put your code here
}
}
3.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>TestServlet</servlet-name>
<servlet-class>luo.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/servlet/TestServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>