Java developer-oriented Ajax:java object serialization (1)

Source: Internet
Author: User
Tags date format object implement json object serialization xml example java web
Ajax|java objects

This article discusses the basics of Ajax development, but will focus on the issues that many Java Web developers are most concerned with: generating data for clients.

Most Java developers have applied the model-view-controller (MVC) pattern to their WEB applications. In a traditional WEB application, the view component consists of a JSP or other presentation technology, such as the Velocity template.

These presentation components update the user interface by dynamically generating completely new HTML pages, replacing the pages that the user was previously viewing. However, in the case of Java WEB applications using the Ajax UI, JavaScript client code is ultimately responsible for updating what the user sees, based on the data received from the XMLHttpRequest response. From the server's perspective, the view becomes the data representation it sends in response to a client request.

This article focuses on techniques that can be used to generate data-centric views of Java objects. I'll demonstrate the various ways you can turn JavaBeans into XML documents, and discuss the pros and cons of each approach. You'll see why XML isn't always the best way: for simple Ajax requests, it's better to transfer plain text.

Finally, I'll also introduce JavaScript object annotations (JSON). JSON allows data to be transmitted in the form of serialized JavaScript object graphs, which is extremely easy to handle serialized JavaScript object graphs in client code.

about the example

I'll use a sample application and several use cases to illustrate the technical features and techniques discussed here. The very simple data model shown in Figure 1 can represent the sample use case. This model represents the customer account in the online store. The customer has a collection of previous orders, each containing several items.

Although XMLHttpRequest has no restrictions on the format used to send data, it is appropriate for most purposes to send only traditional form data, so my discussion is focused on the server's response.

The response can also have text-based formatting, but as its name indicates, XMLHttpRequest has the built-in ability to process XML response data. This makes XML the default choice for Ajax responses, so we start with the discussion from XML format.

generating XML from Java classes

There are many reasons to pass AJAX responses as XML: Each AJAX-enabled browser has a way to navigate XML documents, and there are many server-side technologies that can process XML data.

By developing a scenario that describes the type of document to be exchanged, it is easy to define a contract between the Ajax client and the server, and if the server-side architecture is in a service-oriented manner, using XML can also allow non-AJAX clients to use the data that you provide.

I'll consider three ways to generate XML data from Java objects and discuss the pros and cons of each method.

serialization on its own

First, you can generate XML programmatically from the object graph. This approach can be as simple as implementing the TOXML () method in each JavaBean class. You can then select the appropriate XML API, let each bean provide the element that represents its state, and recursively invoke the object graph on its own members.

Obviously, this approach cannot be extended to a large number of classes, because each class needs to write its own XML generation code specifically. On the plus side, this is a simple way to do it, without additional configuration spending or more complex construction process spending, and any JavaBean graph can become an XML document with just a few calls.

I have concatenated XML tag strings to implement the ToXml () method. As I mentioned last time, this is a bad way to put the burden of ensuring tag pairing, entity coding, and so on in the code for each toXml () method.

There are several XML APIs on the Java platform that can do this for you, so you can focus on the content of the XML. Listing 1 uses the JDOM API to implement the TOXML () in the class that represents the order in the online store example (see Figure 1).

Listing 1. JDOM implementation of the TOXML () of the Order class

Public Element toXml ()

{

Element elorder = new Element ("order");

Elorder.setattribute ("id", id);

Elorder.setattribute

("Cost", Getformattedcost ());



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 you can see how simple it is to create elements with JDOM, to use attributes, and to add element content. The ToXml () method of recursively invoking the composite JavaBean is to obtain the Element representation of their child graphs. For example, the contents of the items element are obtained by calling the TOXML () on each Item object that the order is aggregated.

Once all JavaBean have implemented 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. Generate an XML response from a JDOM element



HttpServletResponse Res)



Servletexception

{



Req.getparameter ("username");

Customer customer =

GetCustomer (CustID);



Customer.toxml ();



New Document (Responseelem);

Res.setcontenttype ("Application/xml");

New Xmloutputter (). Output

(Responsedoc,res.getwriter ());

}
JDOM again makes the work very simple. You only need to wrap a document outside the XML elements returned by the object graph, and then write the documentation to the servlet response with Xmloutputter. Listing 3 shows the XML example generated in this way, initializing Xmloutputter with JDOM Format.getprettyformat (), which is nicely formatted. In this example, the customer made only one order, containing two items.

[1] [2] [3] [4] [5] Next page



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.