This article discusses the basic knowledge of Ajax development, but focuses on the issues that many Java Web developers are most concerned about: generating data for clients.
Most Java developers have applied the Model-View-controller MVC mode to their Web applications. In traditional Web applications, view components are composed of JSP or other presentation technologies such as the Velocity template.
These indicate that the component dynamically generates a brand new HTML page, replacing the page that the user was previously viewing and thus updating the user interface. However, when Java Web applications use Ajax UI, JavaScript client code is ultimately responsible for updating the content seen by users based on the data received from the XMLHttpRequest response. From the server perspective, the view is the data representation it sends in response to client requests.
This article focuses on the technology that can be used to generate a data-centric view of Java objects. I will demonstrate how to convert JavaBeans into XML documents and discuss the advantages and disadvantages of each method. You will see why XML is not always the best way: for simple Ajax requests, it is better to transmit plain text.
Finally, I will introduce the JavaScript Object annotation JSON ). JSON allows data to be transmitted in the form of serialized JavaScript Object graphs. It is extremely easy to process serialized JavaScript Object graphs in client code.
Examples
I will use a sample application and several use cases to demonstrate the technical features and technologies discussed here. Figure 1 shows an extremely simple data model that represents an example case. This model represents the customer account in the online store. A customer has a collection of previous orders. Each order contains several items.
Although XMLHttpRequest does not impose any restrictions on the format used for sending data, it is suitable to send only traditional form data for most purposes. Therefore, my discussion focuses on the server response.
The response can also be in text-based format, but XMLHttpRequest has the built-in ability to process XML response data, as its name indicates. This makes XML the default choice for Ajax response, so we will discuss it from the XML format.
Generate XML from Java class
There are many reasons for passing Ajax responses as XML: Each browser that supports Ajax has a method for navigating XML documents, and many server-side technologies can process XML data.
By developing a scheme to describe the document type to be exchanged, it is easy to define a contract between the Ajax client and the server, and if the server architecture adopts a service-oriented approach, XML allows non-Ajax clients to use your data.
I will consider three methods for generating XML data from a Java object and discuss the advantages and disadvantages of each method.
Serialization by yourself
First, XML can be generated programmatically from the object graph. This method can be as simple as implementing the toXml () method in each JavaBean class. Then, you can select an appropriate xml api to allow each bean to provide elements that represent its own State and recursively call the object graph for its members.
Obviously, this method cannot be extended to a large number of classes, because each class needs to write its own XML to generate code. From a good point of view, this is a simple implementation method, with no additional configuration expenditure or more complex construction process expenditure. Any JavaBean diagram can be changed to an XML document with only a few calls.
I used to connect XML tag strings to implement the toXml () method. As I mentioned last time, this is a bad method because it places the burden of ensuring tag matching, entity encoding, and other work in the code of each toXml () method.
There are several XML APIs on the Java platform to do this for you, so that you can focus on the XML content. Listing 1 uses the jdom api to implement toXml () in the class that represents the order in the online store example. See figure 1 ).
Listing 1. The JDOM implementation of the Order class toXml ()
public Element toXml() { Element elOrder = new Element("order"); elOrder.setAttribute("id",id); elOrder.setAttribute ("cost",getFormattedCost()); Element elDate = new Element("date").addContent(date); elOrder.addContent(elDate); Element elItems = new Element("items"); for (Iterator
iter =
items.iterator() ; iter.hasNext() ; )
{
elItems.addContent(iter.next().toXml());
}
elOrder.addContent(elItems);
return elOrder;
}
|
Here we can see how easy it is to use JDOM to create elements, use attributes, and add element content. Recursively call the toXml () method of the composite JavaBean to obtain the Element representation of their subgraphs. For example, the content of the items element is obtained by calling toXml () on each Item object of Order aggregation.
Once all the JavaBean implementations of the toXml () method, it is easy to serialize any object graph into an XML document and return it to the Ajax client, as shown in Listing 2.
Listing 2. Generating XML responses from the JDOM Element
public void doGet(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException, ServletException { String custId = req.getParameter("username"); Customer customer = getCustomer(custId); Element responseElem = customer.toXml(); Document responseDoc = new Document(responseElem); res.setContentType("application/xml"); new XMLOutputter().output (responseDoc,res.getWriter()); } |
JDOM makes work very simple again. You only need to wrap a Document outside the XML Element returned by the object graph, and then use XMLOutputter to write the Document to the servlet response. Listing 3 shows the XML example generated in this way. The XMLOutputter is initialized using JDOM Format. getPrettyFormat () and formatted very well. In this example, the customer only makes one order and contains two items.