Flex vs. JSON and XML Interoperability __json

Source: Internet
Author: User
Tags eval xml example

Flex is to Java, like the beauty of the brain, or there are other sayings. Who can tell me. All I know is that Flex and Java really work together to create incredibly rich Internet applications (RIA). You'll ask what Flex is. Flex is an open source framework that allows you to build flash applications through the Mxml language (and ActionScript 3).

See:Jack's speech on Flex and JSON and XML Interoperability (QuickTime format, 33MB).

Http://www.jackherrington.com/screencasts/FlexAndJSON.mov

You can download the Flex IDE from Adobe's site (Http://adobe.com/flex), the so-called Flex Builder, and start your development trip. Flex Builder is a commercial product, but it has a long, free trial phase that gives you enough time to figure out if it's worth the money. In this article, I'll show you how to work with Flex and Java together. Java will run on the server side, while flex runs on the client. The communication protocol between the two ends can be any agreement you want. But here, I'll use XML first, and then use JSON, because these two technologies are the most common in the Web 2.0 world.

Creating server Code

The XML example starts with the simple JSP file shown in Listing 1:

Listing 1. xml.jsp





Double compa = 1000.0;
Double COMPB = 900.0;
for (int i = 0; i<=30; i++) {
Compa + + (math.random () * 100)-50;
COMPB + + (math.random () * 100)-50;
]]>


I
Compa
Compb


]]>


This service will export some random stock data to two companies (Compa and COMPB) every 30 days. The first company started with a value of 1000 dollars, and the second started with 900 dollars, and the JSP code added a random number to the two values each day.

When I use the Curl client to access this service from the command line, I get the following result:

% curl "http://localhost:8080/jsp-examples/flexds/xml.jsp"
0966.429108587301
920.7133933216961
...

The root tag is a label that contains a collection of tags. Each label has a label that represents the number of days, a value that represents the stock price of company A, and a value that represents the stock price of Company B. The value of two shares varies with each request because they are randomly generated.

Building an interface

Now that we have a Web service to export the stock price, we also need a client application to show it. The first interface we're going to build is a table-style interface that uses it to simply display numbers. To create a flex project, we chose Flex Project in the Flex Builder IDE's new menu. Displayed as shown in Figure 1:

Figure 1. New Flex Project Dialog box

All we have to do here is give the project a name. I call it xmldg, meaning the XML data table. This creates a file called Xmldg.mxml, which contains only a blank label. I'll use the code in Listing 2 instead of this blank label.

Listing 2. Xmldg.mxml











</mx:application xmlns:mx= "http:>

The XMLDG application code has two main components. The first is the label, which tells Flex that it is an XML data source and provides a URL. This creates a local variable called StockData (specified by the id attribute), and the component can use it as a dataprovider.

The rest of the code is the interface. The object provides a concise wrapper for the table. Which is used to display data. In, is a string of objects to tell the table what data to display.

If we run this interface from Flex Builder, you'll see this look like Figure 2:

Figure 2. XMLDG Application Run Interface

We can pull the scroll bar, change the window size, and see that the data table changes size. If you need to add a bit of filtering functionality, we need to update the code with a control, add a horizontal slider to it, and specify which day the table will start displaying the data.

For example, if we set the slider to 6, it will show only data starting from day sixth. The code looks like Listing 3:

Listing 3. Xmldg2.mxml



<mx:panel title= "Stock Data" width= "100%" height= "100%" layout= "vertical"
Paddingbottom= "paddingleft=" paddingright= "ten" paddingtop= "ten" >












There are other tags, but the rules are basically the same. The label can contain all content. This can be a (horizontal) label, and box also contains and controls. Slider for the Dataprovider field.

Let's take a closer look at the Dataprovider properties:

{StockData.. Day. (Num >= dayslider.value)}

This uses the E4X syntax of ActionScript to reduce the data collection of the control so that it contains only those labels whose values are greater than or equal to the slider value. Flex is very intelligent, it can observe the slider changes events, and automatically update the data table.

When we run this interface from Flex Builder, it looks like Figure 3:

Figure 3. Filter grid

We can adjust the position of the slider and see how the data in the table changes. Figure 4 shows the way I set the slider to 12 o'clock:

Figure 4. Display interface with slider set to 12 o'clock

This is just a simple example of using e4x in ActionScript. The E4X syntax makes processing XML so easy that you are no longer willing to use any other method to process XML.

Draw a chart

The data table is a bit tiring, at least for me. I like to have images. So let's do something--put a chart on the interface. We created a new project called XMLGPH (meaning an XML chart) and replaced the auto-generated xmlgph.xml file with the code in Listing 4.

Listing 4. Xmlgph.mxml



<mx:panel title= "Stock Data" width= "100%" height= "100%" layout= "vertical"
Paddingbottom= "paddingleft=" paddingright= "ten" paddingtop= "ten" >




<mx:linechart id= "Chart" dataprovider= "{stockdata ... Day. (Num >= dayslider.value)} "
Width= "100%" height= "100%" >







The code is the same as XMLDB2, but the control replaces the control to display a numeric chart instead of a table. There is also a control to display the name of the company represented by different color lines. And two objects are similar to the function. They let the linear chart know what data is displayed on which axis.

When we run this interface from Flex Builder, we see this in Figure 5:

Figure 5. Linear legend

It's not bad. Because the control is still there, we can move the position of the slider to change the start date of the chart.

In fact, with just a little bit of change, we can provide the user with two sliders on the slider so that they can move independently to allow the chart to display only data for a certain date. The code appears as shown in Listing 5:

Listing 5. Xmlgph2.mxml




<mx:panel title= "Stock Data" width= "100%" height= "100%" layout= "vertical"
Paddingbottom= "paddingleft=" paddingright= "ten" paddingtop= "ten" >


<mx:hslider minimum= "0" maximum= "id=" Dayslider "snapinterval=" "1"
Thumbcount= "2" values= "[0,30]"/>

<mx:linechart id= "Chart"
Dataprovider= "{StockData. Day. (Num>=dayslider.values[0] &&
NUM<=DAYSLIDER.VALUES[1])} "
Width= "100%" height= "100%" >







All we need to do is add the ThumbCount and values attribute to the tag and update the Dataprovider in the tag. Because this is a piece of XML, I have to encode some of the entities in the Dataprovider. If you run this code from Flex Builder, we'll see what Figure 6 shows:

Figure 6. Window Type line diagram

These are the XML parts of the example demo. Let me begin by demonstrating how to build a flex application that invokes the JSON service.

Building a JSON server

We started by creating a JSON data source to create the JSON reading application. Again, we use a reliable JSP to build JSON-encoded data streams. The JSP code on this section of the server is shown in Listing 6:

Listing 6. json.jsp




[
Double compa = 1000.0;
Double COMPB = 900.0;
for (int i = 0; i<=30; i++) {
Compa + + (math.random () * 100)-50;
COMPB + + (math.random () * 100)-50;
if (i > 0) out.print (",");
]]> {"Compa": Compa, "COMPB": <jsp:expres
SION>COMPB}
]]>
]

This is like XML services, but we're not creating XML tags, but JSON-encoded data.

When I run Curl from the command line, the resulting page looks like this:

% curl "http://localhost:8080/jsp-examples/flexds/json.jsp"
[{"Compa": 992.2139849199265, "COMPB": 939.89135379532}, ...]

And that's exactly what JavaScript clients can understand.

Using the JSON service

Flex is written in the programming language of the Flash Player, ActionScript 3. It's similar to JavaScript, but it doesn't have an eval method. So how do we convert JSON text into ActionScript data? Fortunately, the free ActionScript 3 core library (http://as3corelib.googlecode.com) contains a JSON decoder and a JSON encoder.

The code in Listing 7 illustrates the use of the Jsondecoder object:

Listing 7. Jsondg.mxml

<mx:application xmlns:mx= "Http://www.adobe.com/2006/mxml" layout= "vertical"
Creationcomplete= "Jsonservice.send ()" >

Import mx.rpc.events.ResultEvent;
Import Com.adobe.serialization.json.JSONDecoder;
Private Function Onjsonresult (event:resultevent): void {
var data:string = event.result.toString ();
data = Data.replace (/\s/g, "");
var jd:jsondecoder = new Jsondecoder (data);
Dg.dataprovider = Jd.getvalue ();
}
]]>

<mx:httpservice id= "Jsonservice"
Url= "Http://localhost:8080/jsp-examples/flexds/json.jsp"
resultformat= "text" result= "Onjsonresult (event)"/>








Because the server is returning JSON text, we can't use the tag to get the data. So we're using labels. It works the same way. You need to give it a URL for the service and tell it the format of the result (such as text) and the ActionScript method that the HTTP service needs to invoke when it sends back the response data.

In this example, I specify the Onjsonresult method defined in the label for the result processing method. This method removes all spaces and passes the JSON text to the Jsondecoder object. It then sets the control's dataprovider to the processing result returned by Jsondecoder.

All of this is safe because ActionScript does not support the Eval method. The Jsondecoder class is a simple state machine parser that constructs objects from text in real time. The worst case scenario might be that the process takes a long time if the JSON text is too large.

What's next?

Flex is based on flash, and Flash can interact with any technology. It can interact directly with SOAP-based Web services. It can even communicate binary data with protocols such as the AMF (Adobe message Format).

If this is your first time using Flex, you might want to use flex to build a flash widget and put it on your site to display the data in a more appealing way. To ensure that the flash application size is small enough to facilitate downloading, be sure to use the Runtime shared library (Runtime shared LIBRARY,RSL) in the new version of the Flash Player. This allows you to cache large libraries (such as flex libraries) on the client side and reuse them in different flash applications.

Flex and Java are a powerful combination. Java provides excellent server back-end support. Flex and ActionScript 3 provide a common Cross-platform GUI layer that is easy to write and adopt.

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.