頁面:postingXML.Html
<%@ page contentType="text/Html; charset=GBK" %>
<Html>
<head>
<title>
發送XML請求
</title>
<script type="text/Javascript">
//XMLHttpRequest對象
var XMLHttp;
//創建XMLHttpRequest對象
function createXMLHttpRequest(){
if (window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
//創建XML字串
function createXML(){
var XML = "<pets>"
var options = document.getElementById("petTypes").childNodes;
var option = null;
for (var i = 0; i < options.length; i++){
option = options[i];
if (option.selected){
xml = XML + "<type>" + option.value + "<\/type>";
}
}
xml = XML + "<\/pets>";
return XML;
}
//發送寵物類型請求
function sendPetTypes(){
createXMLHttpRequest();
var xml = createXML();
//處理方法
var url = "postingXMLexample?timeStamp=" + new Date().getTime();
XMLHttp.open("POST",url,true);
XMLHttp.onreadystatechange = handleStateChange;
//設置請求頭格式
XMLHttp.setRequestHeader("Conteyt-Type","application/x-www-form-urlencoded;");
xmlHttp.send(XML);
}
//回調方法
function handleStateChange(){
if (XMLHttp.readyState == 4){
if (XMLHttp.status == 200){
//解析返回結果
parseResults();
}
}
}
//解析返回結果
function parseResults(){
var responseDiv = document.getElementById("serverResponse");
if (responseDiv.hasChildNodes()){
responseDiv.removeChild(responseDiv.childNodes[0]);
}
//返回文本構造一個文本節點
var responseText = document.createTextNode(XMLHttp.responseText);
responseDiv.appendChild(responseText);
}
</script>
</head>
<body bgcolor="#ffffff">
<h1>
請選擇家中寵物的類型:
</h1>
<form action="#">
<select id="petTypes" size="6" multiple="multiple">
<option value="cats">貓</option>
<option value="dogs">狗</option>
<option value="fish">魚</option>
<option value="birds">鳥</option>
<option value="hamsters">鼠</option>
<option value="rabbits">兔</option>
</select>
<br /><br />
<input type="button" value="提交" />
</form>
<h2>服務器端響應:
</h2>
<div id="serverResponse">
</div>
</body>
</Html>
服務器端
PostingXMLExample.Java
import Java.io.*;
import Javax.servlet.*;
import Javax.servlet.http.*;
import Javax.XML.parsers.*;
import org.w3c.dom.*;
public class PostingXMLExample
extends HttpServlet {
private static final String CONTENT_TYPE = "text/Html; charset=GBK";
//Initialize global variables
public void init() throws ServletException {
}
//處理Post請求
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
//得到請求的XML字串
String xml = readXMLFromRequestBody(request);
Document XMLDoc = null;
try {
xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(XML.getBytes()));
}
catch (Exception ex) {
System.out.println("解析XML異常...");
}
//得到類型節點列表
NodeList selectedPetTypes = XMLDoc.getElementsByTagName("type");
String type = null;
String responseText = "選擇的寵物是:";
for (int i = 0; i < selectedPetTypes.getLength(); i++){
type = selectedPetTypes.item(i).getFirstChild().getNodeValue();
responseText = responseText + " " + type;
}
response.setContentType(CONTENT_TYPE);
response.getWriter().print(responseText);
}
/**
* readXMLFromRequestBody
*
* @param request HttpServletRequest
* @return String
*/
private String readXMLFromRequestBody(HttpServletRequest request) {
StringBuffer XML = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null){
XML.append(line);
}
}
catch (Exception ex) {
System.out.println("讀取XML錯誤:" + ex.getMessage());
}
return XML.toString();
}
//Clean up resources
public void destroy() {
}
}