Ajax 传递XML到Java

前两天看了<ajax基础教程>学了不少东西,所以想把例子整理出和大家一起分享:

以下是postingXML.html的内容:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/1999/xhtml">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>Sending an XML Request</title>
  <script type="text/javascript">
   var xmlHttp;
   /**
    *创建XMLHttpRequest对象,此对象是AJAX核心,用于发送异步请求
    *
    */
   function createXMLHttpRequest(){
    if(window.XMLHttpRequest){
     xmlHttp = new XMLHttpRequest();
    }else if (window.ActiveXObject){
     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
   }
   /**
    *生成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+="<type>" +option.value+"<//type>";
     }
    }
    xml+="<//pets>";
    return xml;
   }
   /**
    *发送POST请求
    *
    */
   function sendPetTypes(){
    createXMLHttpRequest();
    var xml=createXML();

   //我的项目叫Ajax1所以应该更改成你的项目名

   //timeStamp=new Date().getTime()是用来生成一个时间戳用于防止url被缓存:因为每次new Date().getTime 方法都会生一个long的值,此值不会重复所以每次的url都是唯一的,所以就不可能去缓存中读数据了。
    var url="/Ajax1/PostingXMLExample?timeStamp="+new Date().getTime();
    xmlHttp.open("POST",url,true);
    xmlHttp.onreadystatechange = handleStateChange;
    //Post请求所必须设置的请求头信息
    xmlHttp.setRequestHeader("Content-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()){
     //删除div中的所有信息为显示最新信息做准备
     responseDiv.removeChild(responseDiv.childNodes[0]);
    }
    //用返回的字符串生成一个文本节点
    var responseText = document.createTextNode(xmlHttp.responseText);
    //把文本节点作为div的子节点显示出来
    responseDiv.appendChild(responseText);
   }
  </script>
 </head>

 <body>
  <form action = "#">
   <select id="petTypes" size="6" multiple="true">
    <option value="cats">Cats</option>
    <option value="dogs">Dogs</option>
    <option value="fish">Fish</option>
    <option value="birds">Birds</option>
    <option value="hamsters">Hamsters</option>
    <option value="rebbits">Rebbits</option>
   </select>
   <br/><br/>
   <input type="button" value="Submit Pets" οnclick="sendPetTypes();"/>
  </form>
  <h2>Server Response:</h2>
  <div id="serverResponse"></div>
 </body>
 
</html>
以下是servlet:PostingXMLExample.java的代码清单:

package servlet;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
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 javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class PostingXMLExample extends HttpServlet {

 /**
  * Constructor of the object.
  */
 public PostingXMLExample() {
  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 {

 }

 /**
  * 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 {
  String xml = readXMLFromResQuestBody(request);
  Document xmlDoc=null;
  try {
   //用字符串生成内存流,再用内存流生成Document对象。Document的parse方法需要流做为参数
   xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));
  } catch (SAXException e) {
   e.printStackTrace();
  } catch (ParserConfigurationException e) {
   e.printStackTrace();
  }
  //得到所有type元素
  NodeList selectedPetTypes = xmlDoc.getElementsByTagName("type");
  String type=null;
  String responseText = "Selected Pets: ";
  for(int i=0;i<selectedPetTypes.getLength();i++){
   //selectedPetTypes.item(i)得到Node对象
   //getFirstChild().getNodeValue()得到Node的值
   type = selectedPetTypes.item(i).getFirstChild().getNodeValue();
   responseText = responseText + " "+type;
  }
  response.setContentType("text/xml");
  PrintWriter out = response.getWriter();
  System.out.println(responseText);
  out.print(responseText);
  
 }
 /**
  * 把请求中的数据通过流读取出来。
  * @param request
  * @return
  */
 private String readXMLFromResQuestBody(HttpServletRequest request){
  StringBuffer xml = new StringBuffer();
  String line = null;
  try{
   BufferedReader reader = request.getReader();
   while((line=reader.readLine())!=null){
    xml.append(line);
   }
  }catch(Exception e){
   System.out.println("Error reading XML:"+e.toString());
  }
  return xml.toString();
 }
 
 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occure
  */
 public void init() throws ServletException {
  // Put your code here
 }

}

这是我的项目。

以下是web.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 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/j2ee
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>PostingXMLExample</servlet-name>
    <servlet-class>servlet.PostingXMLExample</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>PostingXMLExample</servlet-name>
    <url-pattern>/PostingXMLExample</url-pattern>
  </servlet-mapping>

</web-app>
希望对初学者有所帮助。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值