Chinaunix首页 | 论坛 | 博客
  • 博客访问: 273108
  • 博文数量: 53
  • 博客积分: 4010
  • 博客等级: 上校
  • 技术积分: 496
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-06 11:05
文章分类

全部博文(53)

文章存档

2011年(1)

2008年(52)

我的朋友

分类: WINDOWS

2008-04-03 17:21:11

这次我们使用服务器端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+"/";
%>



  
    ">
    
    My JSP 'getXML.jsp' starting page
    
    
    
        
    
    
    

  
  
  //定义用于加载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("您所请求的页面异常");
          }
      }
  }
  
  
  

    


    

    

    


  


然后是服务器端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. 

     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. 

     *
     * 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. 

     *
     * 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. 

     *
     * @throws ServletException if an error occure
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

此servlet生成的xml如下

   


  xuehui0 
  280 
  Male0 
  

  xuehui1 
  281 
  Male1 
  

  xuehui2 
  282 
  Male2 
  

  xuehui3 
  283 
  Male3 
  

  xuehui4 
  284 
  Male4 
  
  


下次我们说说XML的结构和注意事项,最近看CSDN上的<疯狂的程序员>,比较上瘾,已经被领导在工作时间看到多次我在看小说 - - 相信很多朋友可以在绝影身上找到自己当年的影子,毕业在即,心中实在感慨良多,也祝愿绝影兄长完事如意,希望他的故事能鼓舞更多朋友
阅读(1187) | 评论(0) | 转发(0) |
0

上一篇:ajax 入门 1

下一篇:ajax 入门 3

给主人留下些什么吧!~~