本文旨在展示如何使用xml進行請求和相應的數據傳輸,因此並沒有使用復雜的xml解析語法,如何解析和構建XML不是本文的重點;此外,程序沒有對包含對中文內容的處理,關於中文亂碼的問題,我將在接下來的文章中說明。
程序很簡單:
填寫表單–>客戶端構建xml數據,發送請求到服務端–>服務端獲取請求數據,解析並構建xml數據,發送響應–>客戶端獲取響應數據,解析並顯示數據
代碼如下:
xmldemo.jsp
Jsp代碼
<%@ 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>
因為使用Ajax異步通信,所以無需form
xmldemo.js
Jsp代碼
// XMLHttpRequest對象定義
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() {
// 獲取表單數據
var name = document.getElementById("name").value;
var city = document.getElementById("city").value;
// 構建xml格式數據
var xmlString = "<profile>" +
"<name>" + name + "</name>" +
"<city>" + city + "</city>" +
"</profile>";
// 獲取XMLHttpRequest對像
createXmlHttpRequest();
// xmlDemo對應服務端servlet
xmlHttp.open("POST", "xmlDemo", true);
// 指示請求內容為xml格式
xmlHttp.setRequestHeader("Content-type", "text/xml");
// 指定回調函數
xmlHttp.onreadystatechange = updatePage;
// 設定發送的內容
xmlHttp.send(xmlString);
}
// 回調函數定義
function updatePage() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
// 獲取響應數據
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代碼
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對象
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();
}
// 獲取請求參數
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 + "#");
// 構建響應xml格式數據
String xmlData = "<profile>" +
"<name>" + name + "</name>" +
"<city>" + city + "</city>" +
"</profile>";
// 設置響應格式
res.setContentType("text/xml");
PrintWriter out = res.getWriter();
out.println(xmlData);
out.close();
}
}
這裡沒有給出xml文件,因為使用瞭註解方式註冊servlet,如下
Java代碼
@WebServlet("/xmlDemo")
很簡單的一個程序,當然還不完善,但對於理解如何使用xml格式在請求和響應中傳輸數據應該足夠瞭。
作者“lazydoggy”