Ajax基础教程(3)- 3.2 发送请求参数

http://tech.ddvip.com   2007年11月21日    社区交流

内容摘要:要想充分发挥Ajax技术的强大功能,这要求你向服务器发送一些上下文数据。假设有一个输入表单,其中包含需要输入邮件地址的部分。根据用户输入的ZIP编码,可以使用Ajax技术预填相应的城市名。当然,要想查找ZIP编码对应的城市,服务器首先需要知道用户输入的ZIP编码。

  一旦收到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();
  }
  }

来源:CSDN    责编:豆豆技术应用

正在加载评论...