在某些情况下用 jaxp dom api 实现ajax xml响应会是一个很好的选择,可以简化程序.需要用到的jar包javax.xml.parsers.*; org.w3c.dom.*;javax.xml.transform.*;javax.xml.transform.stream.*;javax.xml.transform.dom.*;
前两个包用来创建xml文档,后面几个用来转换到输出流. 以下简要说明用到的方法.然后贴出一个完整实例.
创建新文档 DocumentBuilderFactory factory = DocumentBuilderFactory.
newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
创建root元素 或其它元素 Element root = doc.createElement("selects");
创建根元素 doc.appendChild(root); Element的appendChild()方法用来添加子元素
创建文本结点 doc.createTextNode(String textNode)
在servlet中 通过以下方法转换到输出流 Transformer t = TransformerFactory.newInstance().newTransformer(); t.transform(new DOMSource(doc),
new StreamResult(response.getWriter()));
web.inf 文件配置一个servlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
<display-name>WebModule1</display-name>
<servlet>
<servlet-name>selectservlet</servlet-name>
<servlet-class>drownmenu.SelectServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>selectservlet</servlet-name>
<url-pattern>/selectservlet</url-pattern>
</servlet-mapping>
</web-app>
jsp页面
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<html>
<head>
<title>Ajax 联动下拉框</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<SCRIPT type="text/javascript">
var req;
window.onload=function(){
}
function Change_Select()
{
var zhi=document.getElementById('state').value;
var url="selectservlet?id="+escape(zhi);
if(window.XMLHttpRequest)
{
req=new XMLHttpRequest();
}else if(window.ActiveXObject)
{
req=new ActiveXObject("Microsoft.XMLHTTP");
}
if(req)
{
req.open("GET",url,true);
req.onreadystatechange=callback;
req.send(null);
}
}
function callback()
{
if(req.readyState == 4)
{
if(req.status == 200)
{
parseMessage();
}else{
alert("Not able to retrieve description"+req.statusText);
}
}
}
function parseMessage()
{
var xmlDoc=req.responseXML.documentElement;
var xSel=xmlDoc.getElementsByTagName('select');
var select_root=document.getElementById('city');
select_root.options.length=0;
for(var i=0;i<xSel.length;i++)
{
var xValue=xSel[i].childNodes[0].firstChild.nodeValue;
var xText=xSel[i].childNodes[1].firstChild.nodeValue;
var option=new Option(xText,xValue);
try{
select_root.add(option);
}catch(e){
}
}
}
</SCRIPT>
</head>
<body>
<div align="center">
<form name="form1" method="post" action="">
<TABLE width="70%" boder="0" cellspacing="0">
<TR>
<TD align="center">Ajax 联动下拉框</TD>
</TR>
<TR>
<TD>请选择省份:
<SELECT name="state" id="state" onChange="Change_Select()">
<OPTION value="0">未选择</OPTION>
<OPTION value="1">湖南</OPTION>
<OPTION value="2">湖北</OPTION>
</SELECT>
请选择城市:
<SELECT name="city" id="city">
<OPTION value="0">未选择</OPTION>
</SELECT>
</TD>
</TR>
<TR><td> </td></TR>
</TABLE>
</form>
</div>
</body>
</html>
SelectServlet 类
package drownmenu;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
public class SelectServlet extends HttpServlet {
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String targetId = request.getParameter("id").toString();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/xml");
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.
newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element root = doc.createElement("selects");
doc.appendChild(root);
/*
String xml_start="<selects>";
String xml_end="</selects>";
String xml="";*/
if (targetId.equalsIgnoreCase("0")) {
makeElement(doc, root, new String[] {"未选择"});
// xml = "<select><value>0</value><text>Unbounded</text></select>";
}
if (targetId.equalsIgnoreCase("1")) {
makeElement(doc, root, new String[] {"长沙","岳阳"});
/* xml =
"<select><value>1</value><text>Mana Burn</text></select>";
xml +=
"<select><value>2</value><text>Death Coil</text></select>";
xml +=
"<select><value>3</value><text>Unholy Aura</text></select>";
xml +=
"<select><value>4</value><text>Unholy Fire</text></select>";
*/
}
if (targetId.equalsIgnoreCase("2")) {
makeElement(doc, root, new String[] {"武汉","石堰","襄樊","孝感"});
/*
xml =
"<select><value>1</value><text>Corprxplode</text></select>";
xml +=
"<select><value>2</value><text>Raise Dead</text></select>";
xml +=
"<select><value>3</value><text>Brilliance Aura</text></select>";
xml +=
"<select><value>4</value><text>Aim Aura</text></select>";
*/
} //else {
/*
xml =
"<select><value>1</value><text>Rain of Chaos</text></select>";
xml +=
"<select><value>2</value><text>Finger of Death</text></select>";
xml += "<select><value>3</value><text>Bash</text></select>";
xml +=
"<select><value>4</value><text>Summon Doom</text></select>";
*/
// }
Transformer t = TransformerFactory.newInstance().newTransformer();
t.transform(new DOMSource(doc),
new StreamResult(response.getWriter()));
} catch (Exception ex) {
throw new ServletException(ex.toString());
}
// String last_xml = xml_start + xml + xml_end;
// response.getWriter().write(last_xml);
}
private void makeElement(Document doc, Element root, String[] name) throws
DOMException {
if (name == null) {
return;
}
for (int i = 0; i < name.length; i++) {
Element selectElement = doc.createElement("select");
root.appendChild(selectElement);
Element valueElement = doc.createElement("value");
Element textElement = doc.createElement("text");
int t=i+1;
Text valueText = doc.createTextNode(""+t);
Text textText = doc.createTextNode(name[i]);
valueElement.appendChild(valueText);
textElement.appendChild(textText);
selectElement.appendChild(valueElement);
selectElement.appendChild(textElement);
}
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
//Clean up resources
public void destroy() {
}
}
欢迎加入QQ群:30406099