xml|请求 业务逻辑:下拉框选择喜欢的宠物类型,可多选,选择参数构造成xml参数发送。服务器发回响应结果。
页面: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() {
}
}