Ajax\XML and JSON for Ajax

所需积分/C币:10 2012-02-09 00:46:10 2.28MB PDF
收藏 收藏

Ajax\XML and JSON for Ajax
CHAPTER 4 XML and jSoN for Ajax Do you really need XML for an Ajax application? The previous chapter showed that you don t always need XML. In particular, if you only have one data point, XML is overkill. But the fact is, most web applications deal with multiple data points: user names,passwords, addresses, cities, states, zip codes, etc. How will you decipher those fields when they're sent back from the server? In some cases, passing a string of delimited values may seem like the simplest g XMl has advan For one thing, XML is self-de During debugging, you can look at the XMI string and see exactly what goes where; that is a luxury you wont have with a string of comma-separated values Another reason for using XML is that an XML parser is built into most browsers The parsing work has already been done for you; all you have to do is leverage the built-in parser. Sure, you could pass the data in other formats-Java properties files comma or tab-separated values, yAML files, or a cute custom format that you've designed yourself--but then you would have to write your own parser in JavaScript There is another good way to send data to and from the server: Java a: Script Object Notation (SON). We will discuss JSON toward the end ns of this chapter. The character decoder The example in this chapter is similar to the one in the previous chapter, but instead of the server returning one data point, it's going to return five. Retuning a small col lection of data shows what happens when you go beyond a single data point and illustrates why most Ajax applications need XMl or some other way to structure the data that is passed from the server to the client. Figure 4-1 shows how the user interface of the application will look when were done. The design is simple enough: we send a character to the server using XmLhtTprEquest(), and the server responds with a String containing the five conver sions in XMl format (decimal, octal, hexadecimal, binary, and HTML). The callback()function in the client then calls a function to parse the XMl and popu- late the fields in the b aJAjax On Java, Chapter 4 Example-Microsoft Internet Explorer Fie Edt View Favorites Tools Help Address s h icho4-CharacterDecodt AJAX CHARACTER DECODER Press a key to find its value. Enter key Hi Key Pressed Decimal HeX彐decm Octal HTML Figure 4-1. The complete ajax Character decoder example Now it starts to get fun. One keystroke fills in all the data fields, and although it doesnt look like much is going on from the user's perspective, from the program mer's perspective we know that the application is communicating with the server without a clunky submit or reload or any waiting for the page to refresh Setting Up a Simple XML Document Before we delve into the code, we need to make some decisions. We're going to return data using XML, but how should that XMl be structured? What should our XML response look like? We dont want anything complex, so we'll aim to create an XML document that looks like this <converted-values> <decimal>97/decimal> <hexadecimal,0x61</hexadecimal> <hyper>&amp; OX61; </hyper> binary>1100001B</b Inar> /converted-values> With this format, the browser can use its document object model (dom)parser to ndex and retrieve the data 20 Chapter 4: XML and JSoN for Ajax There are many ways to create this XMl document. For the sake of simplicity, we'll first use a StringBuffer to wrap the data with xml tags later we'll look at other ways to create the xml document c When I talk about XML formatting, I'm referring to the server wrap ping the data in XML. The client receives the XML-formatted string in ; the httPreSpoNse and parses it for the individual data fields The client passes data through the request using either HttPpoSt()or hTtpgEt() There is no reason for the client to send xml data to the server because the data is already wrapped in the request as name/value Using a Servlet to Build an XML Document Let's start by looking at the servlet code that wraps the data in XML. This servlet is shown in Example 4-1 The Ajax responseservlet Converts a character to hex, decimal, binary, octal, and HTML, then k wraps each of the fields with XML and sends them back through the response package com. AJAXb import java. io IOEXception; import javax. servlet ServletException; importjavax.servlethttpHttpservlet; importjavax.servlethttpHttpservletreqUest; importjavax.servlethttpHttpservletreSponse; public class AjaxresponseServlet extends Httpservlet public void doget(Http Servletrequest reg HttpservletreSponse res throws ServletException, IOException i // key is the parameter passed in from the JavaScript // variable named url (see index htm1) String key =req. getParameter("key") StringBuffer returN if(k nu11){ // extract the first character from ke / as an int, then convert that int to a str int keyInt key charAt(o); returnXML new String Buffer ("\r\n<converted-values>" ); turnXML. append ("\r\n<decimal> Integer toString(keyInt)+</decimal> turn XML append ("\r\n<hexadecimal>0x"+ Integer toString(keyInt, 16)+</hexadecimal>") returnXML. append ("\r\n<octal>o"+ (keyInt, 8)+</octal> Setting Up a Simple XML Document2 Example 4-1. The Ajax ResponseServlet (continued) ppend( \r\n<hyper>damp; OX Integer toString(keyInt, 16)+"</hyper>") returrXML. append("\r\n<binary>+ Integer toString(keyInt, 2)+ B</binary> ) eturnXML. append ("\r\n</converted-values"); he response res. setContentTy res setHeader ("Cache-Control","no-cache ) / write out the XML string res.getWriter(). write(returnXML toString ( )) else / if key comes back as a null, return a question mark res setContentType ("text/xnl IessetHeader ("Cache-Control","nO-Cache") res. getWriter().write("? ) This code is similar to the code from Chapter 3 The only thing that has been added is the code to wrap the data with Xml tags returnXML new StringBuffer("\r\n<converted-values> returnXML, append ("\r\n<decimal>+ Integer toString(keyInt)+"</decimal>") returnXML, append ("\r\n<hexadecimal>0x"+ Integer toString(keyInt, 16)+"</hexadecimal>") returnXML. append ("\r\n<octal>o"+ Integer toString(key Int, 8)+</octal>"); returnXML. append("ir\nchyper>&amp; OX"+ Integer tostring(keyInt, 16)+";</hyper> ) returnXML. append ("\r\binary"+ Integer toString(keyInt, 2)+"B</binary>"); returnXML, append ("\r\n</coniverted-values>") This code simply sets up a StringBuffer called returnXML. We then convert the incoming value to decimal, hex, etc. wrap it with an appropriate XML tag; and append it to the buffer. When we've finished all five conversions and added the clos ing tag (</ converted-values>), we send the response back to the ajax client using res.getWriter().write(). We return a question mark (without any XMl wrapping) if the key we received was null Other Ways to build the xml document Building an XMl document by appending to a StringBuffer is a common approach but it's far from ideal, particularly if you need to generate a large document program- matically. Fortunately, there are alternatives 22 Chapter 4: XML and JSON for Ajax JDOM One option is to use the jDOM library to write the XML. download the jdom. jar file fromhttp:/www.jdom.organdputitinyourapplicationsWeb-inF/liBdirectory Then, instead of writing to a String Buffer, use JDOM to build the XMl, as shown in Example 4-2 xample 4-2. Using DOM to create the XMl document / additional imports needed for JDOM import org. jdom. Document import org. jdom Element import org. jdom output. XMLOutputter; public String create]domXML(int key) throwS IOException Document document new Document o; // create root node t= new org.jdom Element( document set Root E lement(root) / create your node org. jdom Element element new org. jdon Element("decimal") / add content to the node element. addContent(Integer toString(key)) / add your node to root root. add Content(element element= new org. jdom Element("hexadecimal") element. addContent( Integer toString(key, 16)) element. addcontent ("0"+ Integer to String(key, 8)) root. addContent(element); element Org·jdon element. addCoritent("&ox"+ Integer tostring(key, 16); element new org. jdom Element("binary " ) element. addContent(Integer tostring(key, 2)+"B") root. add Content(element); // output JDOM document as a String of bytes XMLOutputter outputter= new XMLOutputter(); return outputter. outputString( document) In the preceding code, we first create a Document (org. jdom. Document), then an Element named root with the String"converted-values"as its value. That element becomes the root of the xml document here's what the document looks like at this <converted-values> Setting Up a Simple XML Document23 To add child elements to the root we create new elements and add them to the root element. The code that creates the decimal element and adds it to the root element looks like this org. jdam. E lement element new org. jdom Element ("decimal"); element. add Content(integer tostring(key) root. addContent(element) We repeat this process until we 've added all the elements to the root then we use an XMLOutputter to format the document into a String that we can send back to the cl ent. The jDOM XMl document now looks like this(with lineleeds and spaces added for readabili o"encoding="UTF-8 <converted-values> <decimaly97</decimal> <hexadecimal l>0x61</hexadecimal> tal>0141</octal <binary>1100001B</binary> </converted-values> dom4j dom4j is an XMl library similar in intent to JDOM. After downloading dom 4j from http://www.dom4j.org/download.htmlandinstallingitinyourapplicationsWeb INF/Lib directory, you can use it to create your XML document. As shown in Example 4-3, we create a document, add a root element to the document, add the elements and data to the root, and then return the document in a String Example 4-3. Using dom4j to create the XMl document // additional imports for dom4j t org. dom4j Document ort org. dom4j. DocumentHelper; import org.dom4j Document Exception Imao rt org. dom4j Element; import org. dom4]. io OutputFormat import org. dom4j io XMLWriter; public String createDom4jXML(int key) throws IOException t Documentdocument- DocumentHelper createDocument (; Element root =document. addElement("converted-values"); Element element root addElement ("decimal").addText nteger tostring(key)) element root addElement ("hexadecimal").addText( Ox"+ Integer toString(key, 16)) element root addElement("octal" ). addText("O"+ Integer tostring(key, 8)); element root addElement("hyper"). addText("&Ox"+ Integer tostring(key, 16)) 24 Chapter 4: XML and JSoN for Ajax Example 4-3. Using dom4j to create the XMl document(continued) element root addElement ("binary").addText(Integer toString(key, 2)+"B") StringBuffer xmldoc null Stringwriter sw new StringWriter() OutputFormat outformat= OutputFormat create Prettyprint (; XMLWriter writer- new XMLWriter(sW, out format); citer write document) writer. close() xmlDoc= SW. getBuffer (; return xmlDoc. toString (); The dom4j library uses the static method DocumentHelper createDocument()to cre ate the XMl document. The method root. addElement()puts a child element on the root element, and addText()puts the data in the elements. The OutputFormat class then used to format the Xmldocument. so the document looks like this. ncoding=UTF-8 <converted-values> <decimal>97</de <hexadecimal>0x61</hexadecimal> hyper> &amp; 0x61</h <binary>1100001B</binary> </converted-values> This step can be skipped, because it only formats the document for readability by adding linefeeds and spaces. Since humans shouldn't need to read this document (unless you are debugging), you wont need the formatting To use dom4 without the formatting, simply replace these two lines outputFormat outformat= outputFormat. createPrettyPrint() XMLWriter writer= new XMLWriter (sw, outformat ) with this line XMLWriter writer new XMLWriter(sw); SAX SAX, the Simple aPI for XML, provides another way to create an XML document for an Ajax application. It may be faster than JDOM or dom 4J, because it doesn't require building a DOM tree for your document. Start by initializing a StringWriter and a streamResult initialize the streamResult with the streamWriter then get a SAXTransformerFactory and get a TransformerHandler trom that. The Trans formerHandler allows you to create an XMI document by starting a docu ment and appending elements and data to the TransformerHandler. Example 4-4 shows how it works Setting Up a Simple XML Document25

试读 25P Ajax\XML and JSON for Ajax
立即下载 身份认证VIP会员低至7折
关注 私信
Ajax\XML and JSON for Ajax 10积分/C币 立即下载
Ajax\XML and JSON for Ajax第1页
Ajax\XML and JSON for Ajax第2页
Ajax\XML and JSON for Ajax第3页
Ajax\XML and JSON for Ajax第4页
Ajax\XML and JSON for Ajax第5页

试读结束, 可继续读3页

10积分/C币 立即下载