3.2 发送请求参数(三)


一旦收到XMLHttpRequest对象的请求,就会调用这个servlet的doPost方法。doPost方法使用名为readXMLFromRequestBody的辅助方法从请求体中抽取XML,然后使用JAXP接口将XML串转换为Document对象。

  注意,Document对象是W3C指定的Document接口的一个实例。因此,它与浏览器的Document对象有着同样的方法,如getElementsByTagName。可以使用这个方法来得到文档中所有type元素的列表。对于文档中的每个type元素,会得到文本值(应该记得,文本值是type元素的第一个子节点),并逐个追加到串中。处理完所有type元素后,响应串写回到浏览器。

  代码清单3-10 PostingXMLExample.java

  package ajaxbook.chap3;
  import java.io.*;
  import javax.servlet.*;
  import javax.servlet.http.*;
  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 {
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  String xml = readXMLFromRequestBody(request);
  Document xmlDoc = null;
  try {
  xmlDoc =
  DocumentBuilderFactory.newInstance().newDocumentBuilder()
  .parse(new ByteArrayInputStream(xml.getBytes()));
  }
  catch(ParserConfigurationException e) {
  System.out.println("ParserConfigurationException: " + e);
  }
  catch(SAXException e) {
  System.out.println("SAXException: " + e);
  }
  /* Note how the Java implementation of the W3C DOM has the same methods
  * as the JavaScript implementation, such as getElementsByTagName and
  * getNodeValue.
  */
  NodeList selectedPetTypes = xmlDoc.getElementsByTagName("type");
  String type = null;
  String responseText = "Selected Pets: ";
  for(int i = 0; i < selectedPetTypes.getLength(); i++) {
  type = selectedPetTypes.item(i).getFirstChild().getNodeValue();
  responseText = responseText + " " + type;
  }
  response.setContentType("text/xml");
  response.getWriter().print(responseText);
  }
  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 e) {
  System.out.println("Error reading XML: " + e.toString());
  }
  return xml.toString();
  }
  }

 3.2.2 使用JSON向服务器发送数据

  做了这么多,你已经能更顺手地使用JavaScript了,也许在考虑把更多的模型信息放在浏览器上。不过,看过前面的例子后(使用XML向服务器发送复杂的数据结构),你可能会改变主意。通过串连接来创建XML串并不好,这也不是用来生成或修改XML数据结构的健壮技术。

  JSON概述

  XML的一个替代方法是JSON,可以在www.json.org找到。JSON是一种文本格式,它独立于具体语言,但是使用了与C系列语言(如C、C#、JavaScript等)类似的约定。JSON建立在以下两种数据结构基础上,当前几乎所有编程语言都支持这两种数据结构:

  l  名/值对集合。在当前编程语言中,这实现为一个对象、记录或字典。

  l  值的有序表,这通常实现为一个数组。

  因为这些结构得到了如此众多编程语言的支持,所以JSON是一个理想的选择,可以作为异构系统之间的一种数据互换格式。另外,由于JSON是基于标准JavaScript的子集,所以在所有当前Web浏览器上都应该是兼容的。

  JSON对象是名/值对的无序集合。对象以 { 开始,以 } 结束,名/值对用冒号分隔。JSON数组是一个有序的值集合,以[ 开始,以 ] 结束,数组中的值用逗号分隔。值可以是串(用双引号引起)、数值、true或false、对象,或者是数组,因此结构可以嵌套。图3-6以图形方式很好地描述了JSON对象的标记。

                                                   

 图3-6 JSON对象结构的图形化表示

  请考虑employee对象的简单例子。employee对象可能包含名、姓、员工号和职位等数据。使用JSON,可以如下表示employee对象实例:

  var employee = {
  "firstName" : John
  , "lastName" : Doe
  , "employeeNumber" : 123
  , "title" : "Accountant"
  }

  然后可以使用标准点记法使用对象的属性,如下所示:

  var lastName = employee.lastName;  //Access the last name
  var title = employee.title;       //Access the title
  employee.employeeNumber = 456;    //Change the employee number

  JSON有一点很引以为豪,这就是它是一个轻量级的数据互换格式。如果用XML来描述同样的employee对象,可能如下所示:

  <employee>
  <firstName>John</firstName>
  <lastName>Doe</lastName>
  <employeeNumber>123</employeeNumber>
  <title>Accountant</title>
  </employee>

  显然,JSON编码比XML编码简短。JSON编码比较小,所以如果在网络上发送大量数据,可能会带来显着的性能差异。

  

本文作者:
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3