这次我们使用服务器端servlet来生成一个XML
并在前台页面上使用ajax技术来请求这个servlet,获得它,然后使用javascript来解析它,获得我们需要的信息,其中内容我参考了《基于J2EE的AJAX宝典》,这里向 李刚 大哥说声谢谢,是本好书,推荐ajax初学者买一本细读,其中详细的介绍了javascrpit和CSS,很适合前台技术入门者阅读,还希望技术论坛上不要有人像优酷等大众论坛上的人一样,动不动就说人是“枪手”,生成servlet是一位不知名的仁兄的blog,也谢谢他
首先来看一下页面
内容重点在回调函数中,只有几个方法的使用
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'getXML.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<script type="text/javascript">
//定义用于加载xml文档的函数
//定义初始化XHR对象
var xmlrequest;
function createXMLHttpRequest(){
if(window.XMLHttpRequest){
//mozilla 浏览器
xmlrequest = new XMLHttpRequest();
}else if(window.ActiveXObject){
//IE浏览器
try{
xmlrequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlrequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
}
}
}
}
function getXML(){
//初始化XHR对象;
createXMLHttpRequest();
//设置请求响应的URL
var uri="buildXMLAction";
//打开与服务器响应地址的链接
xmlrequest.open("POST",uri,true);
//设置请求头
xmlrequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//设置处理响应的回调函数
xmlrequest.onreadystatechange = processResponse;
//发送请求
xmlrequest.send(null);
}
function processResponse(){
//判断相应是否完成
if(xmlrequest.readyState == 4){
//判断响应是否成功
if(xmlrequest.status == 200){
//信息已经成功返回,开始处理信息
//此处使用responseXML属性来获得一个XML文档对象
var xmlObj = xmlrequest.responseXML;
//将此对象解析成为”文档”,笔者也不是很清楚为什么这么用
var xmlDoc=xmlrequest.responseXML.documentElement; //这里我们使用一个alert来输出信息,首先是xmlDoc.getElementsByTagName(“user”)这个方法返回一个数组,后面的[0]什么的自节点什么的大家动手调一调就明白了,不过结构细节我现在也很糊涂
alert(xmlDoc.getElementsByTagName("user")[0].childNodes[0].childNodes[0].nodeValue);
// 控制user 控制name,age,sex 内容
}else{
//页面不正常
window.alert("您所请求的页面异常");
}
}
}
</script>
<body>
<input type="button" value="getXML" onclick="getXML()"/><br>
<div id="outputxml"></div><br>
<br>
<br>
<div id="outputtext"></div><br>
</body>
</html>
然后是服务器端servlet
请求路径在open函数里, var uri="buildXMLAction";
这里千万要注意的是
response.setContentType("text/xml");
以上这句不可写成
response.setContentType("text/html");
import java.io.FileOutputStream;
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 org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
public class buildXMLAction extends HttpServlet {
/**
* Constructor of the object.
*/
public buildXMLAction() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/xml");
PrintWriter out = response.getWriter();
// 创建根节点 list;
Element root = new Element("list");
// 根节点添加到文档中;
Document Doc = new Document(root);
// 此处 for 循环可替换成 遍历 数据库表的结果集操作;
for (int i = 0; i < 5; i++) {
// 创建节点 user;
Element elements = new Element("user");
// 给 user 节点添加属性 id;
elements.setAttribute("id", "" + i);
// 给 user 节点添加子节点并赋值;
// new Element("name")中的 "name" 替换成表中相应字段,setText("xuehui")中 "xuehui 替换成表中记录值;
elements.addContent(new Element("name"+i).setText("xuehui"+i));
elements.addContent(new Element("age"+i).setText("28"+i));
elements.addContent(new Element("sex"+i).setText("Male"+i));
// 给父节点list添加user子节点;
root.addContent(elements);
}
XMLOutputter XMLOut = new XMLOutputter();
// 输出 user.xml 文件;
XMLOut.output(Doc, out);
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
}
此servlet生成的xml如下
<?xml version="1.0" encoding="UTF-8" ?>
- <list>
- <user id="0">
<name0>xuehui0</name0>
<age0>280</age0>
<sex0>Male0</sex0>
</user>
- <user id="1">
<name1>xuehui1</name1>
<age1>281</age1>
<sex1>Male1</sex1>
</user>
- <user id="2">
<name2>xuehui2</name2>
<age2>282</age2>
<sex2>Male2</sex2>
</user>
- <user id="3">
<name3>xuehui3</name3>
<age3>283</age3>
<sex3>Male3</sex3>
</user>
- <user id="4">
<name4>xuehui4</name4>
<age4>284</age4>
<sex4>Male4</sex4>
</user>
</list>
下次我们说说XML的结构和注意事项,最近看CSDN上的<疯狂的程序员>,比较上瘾,已经被领导在工作时间看到多次我在看小说 - - 相信很多朋友可以在绝影身上找到自己当年的影子,毕业在即,心中实在感慨良多,也祝愿绝影兄长完事如意,希望他的故事能鼓舞更多朋友