Ajax在请求和响应中使用XML示例
程序员文章站
2022-06-10 09:14:52
...
本文旨在展示如何使用xml进行请求和相应的数据传输,因此并没有使用复杂的xml解析语法,如何解析和构建XML不是本文的重点;此外,程序没有对包含对中文内容的处理,关于中文乱码的问题,我将在接下来的文章中说明。
程序很简单:
填写表单-->客户端构建xml数据,发送请求到服务端-->服务端获取请求数据,解析并构建xml数据,发送响应-->客户端获取响应数据,解析并显示数据
代码如下:
xmldemo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Ajax with XML</title> <script type="text/javascript" src="js/xmldemo.js"></script> </head> <body> <table align="center"> <tr> <td>Name</td> <td><input type="text" name="name" id="name"/></td> </tr> <tr> <td>City</td> <td><input type="text" name="city" id="city"/></td> </tr> <tr> <td colspan="2"><input type="button" value="Submit" onclick="callServer()"/></td> </tr> </table> </body> </html>
因为使用Ajax异步通信,所以无需form
xmldemo.js
// XMLHttpRequest对象定义 var xmlHttp = false; function createXmlHttpRequest() { try{ xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try{ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e2) { xmlHttp = false; } } if(!xmlHttp && typeof XMLHttpRequest != "undefined") { xmlHttp = new XMLHttpRequest(); } } function callServer() { // 获取表单数据 var name = document.getElementById("name").value; var city = document.getElementById("city").value; // 构建xml格式数据 var xmlString = "<profile>" + "<name>" + name + "</name>" + "<city>" + city + "</city>" + "</profile>"; // 获取XMLHttpRequest对像 createXmlHttpRequest(); // xmlDemo对应服务端servlet xmlHttp.open("POST", "xmlDemo", true); // 指示请求内容为xml格式 xmlHttp.setRequestHeader("Content-type", "text/xml"); // 指定回调函数 xmlHttp.onreadystatechange = updatePage; // 设定发送的内容 xmlHttp.send(xmlString); } // 回调函数定义 function updatePage() { if(xmlHttp.readyState == 4) { if(xmlHttp.status == 200) { // 获取响应数据 xmlDoc = xmlHttp.responseXML; var nameElement = xmlDoc.getElementsByTagName("name").item(0); var name = nameElement.firstChild.nodeValue; var cityElement = xmlDoc.getElementsByTagName("city").item(0); var city = cityElement.firstChild.nodeValue; alert("Name : " + name + "\n" + "City : " + city); } else { alert("Error : status code is " + xmlHttp.status); } } }
XmlDemoServlet.java
package com.ajaxdemo.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; import com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl; /** * Servlet implementation class XmlDemoServlet */ @WebServlet("/xmlDemo") public class XmlDemoServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public XmlDemoServlet() { super(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } private void processRequest(HttpServletRequest req, HttpServletResponse res) throws IOException { // Document对象 Document doc = null; DocumentBuilderFactory dbf = new DocumentBuilderFactoryImpl(); try { DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(req.getInputStream()); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 获取请求参数 Node nameElement = doc.getElementsByTagName("name").item(0); String name = nameElement.getFirstChild().getNodeValue(); Node cityElement = doc.getElementsByTagName("city").item(0); String city = cityElement.getFirstChild().getNodeValue(); // System.out.println("# " + name + " " + city + "#"); // 构建响应xml格式数据 String xmlData = "<profile>" + "<name>" + name + "</name>" + "<city>" + city + "</city>" + "</profile>"; // 设置响应格式 res.setContentType("text/xml"); PrintWriter out = res.getWriter(); out.println(xmlData); out.close(); } }
这里没有给出xml文件,因为使用了注解方式注册servlet,如下
@WebServlet("/xmlDemo")
很简单的一个程序,当然还不完善,但对于理解如何使用xml格式在请求和响应中传输数据应该足够了。