分享

30 分钟教会你Flex和java沟通 (附例子)

 WindySky 2007-04-12
来源: http:///testdrive/flex4j/index.htm


30 Minutes Flex Test-Drive for Java DevelopersBy Christophe Coenraets
Last update: September 6th, 2006

The objective of this test-drive is to give you, in a very shortamount of time, an understanding of how Flex works and what it can do.This test-drive consists of a series of samples kept as concise aspossible (typically between 10 and 50 lines of code) to clearly exposefeatures of interest. The samples focus primarily on using Flex with aJava back-end. The intended audience is Java developers with no priorknowledge of Flex.
A few things to know before you start...
  • The Flex programming model is made of:
    • MXML, an XML language used to declaratively lay  out the user interface of your application.
    • ActionScript,an ECMAScript compliant, object-oriented programming model. With somesyntactical differences, ActionScript looks and feels similar to Java,and supports the same object-oriented constructs: packages, classes,inheritance, interfaces, strong (but also dynamic) typing etc.
    • An extensive set of class libraries. The online API documentation is available here in a Javadoc-like format.
  TheFlex source code (.mxml and .as files) is compiled into Flash bytecode(.swf) that is executed at the client-side by the Flash virtual machine.There are different ways you can use the Flex compiler (mxmlc):
  • From the command line
  • As part of   an ant script
  • Using FlexBuilder: the compilation process is  integrated in the IDE
  • Usingthe web compiler (available with the Flex Data Services). This issimilar to the JSP compilation model: The first time an application isrequested it is compiled into bytecode, which is then cached to servesubsequent requests.
You typically don‘t usethe web compiler in a production environment. However, we are using itin this test-drive to minimize the number of components to install onyour machine (all you will need to install is a war file).
The Flex product line includes:
  • The Flex SDK which is free and  includes the Flex libraries, the compiler (mxmlc), the debugger, and the  documentation.
  • Flex Data Services(FDS), an optional set of server-side components deployed in your J2EEapplication server. FDS includes a Java RPC service (sample 3),publish/subscribe messaging (samples 6 and 7), and data managementservices (sample 8). FDS is free for a single-CPU deployment (FDSExpress), and is licensed per CPU when deployed on multiple CPUs.
  • FlexBuilder,an optional IDE for Flex development. Built as an Eclipse plug-in,FlexBuilder includes a design view and a code view, code hinting,visual debugging, etc. FlexBuilder is licensed on a per developerbasis.
  • Optional charting components licensed on a per developer basis.
    Youcan develop and deploy Flex applications entirely for free using theSDK and the IDE of your choice. I will highlight the examples in thistest-drive that require the Flex Data Services.
  Installing the Test Drive FilesSince we will be using the Flex Data Services, you need a J2EE server, or, at a minimum, a Servlet container.
  • Download the testdrive war file.
    • If you usean application server that implements the full J2EE stack (IBMWebsphere, BEA Weblogic, JBoss, JRun, etc.), download the versionbelow. It includes the Flex Data Services, the sample applications, andan embedded HSQLDB database to support the samples. Proceed to license and download
    • If you use Tomcat 5.5.x,download the version below. It includes the Flex Data Services, thesample applications, an embedded HSQLDB database to support thesamples, and JOTM (an opensource implementation of the Java Transaction API required by the datamanagement services wich are used in sample 8). Proceed to license and download
    • If you use Tomcat 5.0.x,download the version below. It includes the Flex Data Services, thesample applications, an embedded HSQLDB database to support thesamples, and JOTM (an open source implementation of the Java Transaction API required by the data management services wich are used in sample 8):    Proceed to license and download
    Note:the only difference between the 5.5.x and 5.0.x version is theconfiguration of JOTM in META-INF\context.xml (the way you configureUserTransaction has changed in Tomcat 5.5).
  Deploy testdrive.war in your application serverAccess http://localhost:8080/testdrive (change the host name and port number as appropriate).
  Sample  1: Accessing data using HTTPService  Run the sample:  
  • Access  http://localhost:8080/testdrive/sample1/SampleXML.mxml    Noticethat there is a delay the first time you access an application in thistest-drive. This is because we are using the web compiler whichcompiles your application into bytecode the first time it is accessed(similar to the JSP compilation model). Subsequent requests to the sameapplication will be much faster since the application is alreadycompiled. In a production environment, you would typically deployprecompiled applications.
            Noteepending on your configuration, you may need to increase the heap sizeof your application server‘s JVM to use the web compiler. This wouldnot be required in a production environement since you typically don‘tuse the web compiler. If you get a java.lang.OutOfMemoryErrorexception while trying to access a sample for the first time, you mustincrease your heap size.
  • Click "Get Data": The DataGrid is populated with XML data returned by catalog.jsp
  • Also notice some of the built-in DataGrid  features:
    • Sortable columns  (click on a column header)
    • Moveable columns (click on a column header and, with the mouse button pressed, move the column to a new position)
  Code walkthrough:Open the following files in a code editor:
  • testdrive/sample1/SampleXML.mxml
  • testdrive/sample1/catalog.jsp
Using HTTPService, you can send HTTP requests to a server, andconsume the response. Although the HTTPService can be used to consumedifferent types of responses, it is typically used to consume XML. Youcan use the HTTPService with any kind of server-side technology: JSP,Servlet, ASP, Ruby on Rails, PHP, etc. You specify the target servicein the url property of HTTPService.
Flex provides sophisticated data binding capabilities. You can bindthe value of a property to the value of another property, or to anexpression in general. In this example, the dataProvider property ofthe DataGrid is bound (using the curly braces notation) to thelastResult property of the HTTPService.
HTTPService calls are asynchronous. The result event is triggered on the HTTPService  when the data becomes available to the client application. The faultevent is triggered if an error occurs at the server-side, or if thenetwork becomes unavailable. (See sample 5, for an example of codingresult and fault event handlers).
By default, the XML document retrieved from the server isdeserialized into an object graph. This allows you to navigate throughthe result using the dot notation. You can also get the result as anXML document by specifying resultFormat="e4x" on the HTTPService. Inthat case, you can parse the document using E4X (ECMAScript for XML).
More info:
  • Both HTTP and HTTPS are supported
  • Instead ofusing the url property to specify a hardcoded URL, you can specify alogical name in the destination property. You then map this logicalname to an actual URL in WEB-INF\flex\proxy-config.xml. In thisexample, you could replace url="catalog.jsp" with destination="catalog"(open WEB-INF\flex\proxy-config.xml to see how the catalog destinationis configured). As another example, to get the headlines from the NewYork Times, specify destination="news", and change the DataGrid databinding to: dataProvider="{srv.lastResult.rss.channel.item}".

  
  Sample 2: Accessing data using Web Services  Run the sample: Code walkthrough:Open the following file in a code editor:
  • testdrive/sample2/SampleWebService.mxml
Access the wsdl file for the web service  used in this example:
Using the WebService tag, you can invoke SOAP-based web servicesdeployed in your application server or on the internet. Objectsreturned by a web service are automatically deserialized intoActionScript objects. Similarly ActionScript objects passed asarguments to a web service operation are serialized according the wsdldescription.
Notice that we also added DataGrid column definitions (using DataGridColumn) in this example.
More Info:
  • Flex supports both RPC-encoded and document-literal web services
  • Like HTTPService, WebService calls are asynchronous: You can code result and fault event handlers
  • Likewhen using HTTPService, you can use a logical name instead of ahardcoded URL to identify the service, and map the logical name inWEB-INF\flex\proxy-config.xml.


  Sample  3: Accessing data using Java RPC  Run the sample: Code walkthrough:Open the following files in a code editor:
  • sample3\SamplePOJO.mxml
  • WEB-INF\src\flex\testdrive\store\ProductService.java
  • WEB-INF\flex\remoting-config.xml
Using RemoteObject, you can directly invoke methods of Java objectsdeployed in your application server, and consume the return value. Thereturn value can be a value of a primitive data type, an object, acollection of objects, an object graph, etc.
The value of the destination property of RemoteObject is a logicalname that is mapped to a fully qualified java class inremoting-config.xml.
Java objects returned by server-side methods are deserialized intoeither dynamic or typed ActionScript objects. In this example, we don‘thave an explicit ActionScript version of the Product Java class.Product objects are therefore deserialized into dynamic objects. Insample 5, we work with an explicit Product class in ActionScript.
More info:
  • Like HTTPService and WebService, RemoteObject calls are asynchronous. You use the result and fault events of the RemoteObject to handle results and errors (see sample 5).  

  
  Sample  4: Flex Programming Model 101   Run the sample: Code walkthrough:Open the following files in a code editor:
  • sample4\MasterDetail.mxml
  • sample4\Thumb.mxml
  • sample4\ProductView.mxml
Like in any other object-oriented programming language, a Flexapplication is made of a collection of classes. Using Flex, you cancreate classes using MXML or ActionScript. You typically create viewclasses in MXML, and Model and Controller classes in ActionScript.
When you create an mxml file, you are actually creating a class. Theroot node of the mxml document indicates the class you extend. Forexample, creating a file named MasterDetail.mxml with an<Application> root node is equivalent to creating an ActionScriptclass with the following signature:
  public class MasterDetail extends Application {
  }

Similarly, creating a file named ProductView.mxml with a<anel> root node is similar to creating a class with thefollowing signature:
  public class ProductView extends Panel {
  }

Once you have defined a class, you can use it programatically ordeclaratively (as a tag in MXML) without the need for an additionaldescriptor file. Public properties are automatically available as tagattributes. For example, in MasterDetail.mxml, we define the<roductView> tag and bind its product attribute to the selecteditem in the product list.
Also notice the support for CSS style sheets.

  
  Sample 5: Updating Data  Run the sample:    Code walkthrough:Open the following files in a code editor:
  • sample5\SampleUpdate.mxml
  • sample5\ProductForm.mxml
  • sample5\Product.as
  • WEB-INF\src\flex\testdrive\store\ProductService.java
  • WEB-INF\flex\remoting-config.xml
In Product.as we use the[RemoteClass(alias="flex.testdrive.store.Product")] annotation to mapthe ActionScript version of the Product class (Product.as) to the Javaversion (Product.java). As a result, Product objects returned by thegetProducts() method of ProductService are deserialized into instancesof the ActionScript Product class. Similarly, the instance of theActionScript Product class passed as an argument to the update methodof the RemoteObject is deserialized into an instance of the javaversion of the Product class at the server-side.

  
  Sample 6: Publish/Subscribe Messaging (Data Push Use Case)  Run the sample:  In this example, a Java component publishes simulated real time valuesto a message queue. The Flex client subscribes to that queue anddisplays the values in real time.
     Code walkthrough:  Open the following files in a code editor:
  • sample6\FeedClient.mxml
  • WEB-INF\src\flex\testdrive\feed\Feed.Java
  • WEB-INF\flex\messaging-config.xml
Flex supports publish/subscribe messaging through the Flex MessageService (part of the Flex Data Services). The Flex Message Servicemanages a set of destinations that Flex clients can publish andsubsribe to. Flex provides two components, Producer and Consumer, thatyou use to respectively publish and subscribe to a destination. Tosubscribe to a destination, you use the subscribe() method of theConsumer class. When a message is published to a destination yousubscribed to, the message event is triggered on the Consumer.
In Feed.java, the Flex Java API (MessageBroker, AsyncMessage) isused to publish messages to the Flex destination. The Javadocdocumentation for the Java API is available here.Another option to exchange messages bewteen Flex and Java applicationsis to map Flex destinations to JMS topics, essentially allowing a Flexclient to publish and subscribe to JMS topics. In addition to JMS, theFlex Message Service adapter architecture allows you to integrate withany kind of messaging system.
Flex destinations are configured in messaging-config.xml. You canconfigure a destination to deliver the messages using a real-timeprotocol or using polling.
Additional resources: Check out the portfolio viewer sample for a more complete example of data push.

  
  Sample 7: Publish/Subscribe Messaging (Collaboration Use Case)   Run the sample:   Code walkthrough:Open the following files in a code editor:
  • sample7\Chat.mxml
  • WEB-INF\flex\messaging-config.xml
This sample builds on the concepts and APIs introduced in theprevious example. To publish a message from a client, you use thesend() method of the Producer class.
The messaging and real time infrastructure available in Flex enablescollaboration and data push applications to be built in a scalable andreliable manner while preserving the lightweight web deployment model.
Additional resources: Check out the Google Map collaboration sample.


  Sample 8: Data Management Services  Testing persistence:    Testing data synchronization across clients:
  • Open the same application in a second browser window
  • Resize  the two browser windows  so that you can see both at the same time on your screen
  • Modify data  in one browser, and press Enter: notice that the update is automatically pushed to the other client
Code walkthrough:Open the following files in a code editor:
  • sample8\SampleDataService.mxml
  • sample8\Product.as
  • WEB-INF\src\flex\testdrive\store\ProductAssembler.java
  • WEB-INF\src\flex\testdrive\store\ProductService.java
  • WEB-INF\flex\data-management-config.xml
In addition to the RPC services described in samples 1, 2, and 3,the Flex Data Management Services provide an innovative and highlyproductive approach to synchronize data across tiers and betweenclients. The Flex Data Management Services consist of a client-side APIand server-side services:
At the client-side, "managed objects" keep track of changes made tothe data, and notify the back-end of these changes. InSampleDataService.mxml, all you have to do is:
  • Define a DataService pointing to the "product" destination defined in data-management-config.xml
  • Invoke the DataService‘s fill() method to populate the "products" array
  • Bind  the DataGrid to the products array
You don‘t have to keep track of changes made to the data, nor do youhave to invoke remote services to notify the back-end of the changes(create, update, delete) made at the client side.
At the server-side, the Data Service receives the list of changesand passes it to your server-side persistence components. The DataService also pushes the changes to other clients. In this example, the"product" DataService configured in data-management-config.xml uses thejava-dao adapter, indicating that we will take care of the persistencecode with our own Java classes (another option is to use the Hibernateadapter). There is no specific contract imposed on the Java class thatprovides the persistence implementation: You map methods such as filland sync to actual methods in an assembler class (in this caseroductAssembler). In the assembler class, you typically delegate theactual persistence implementation to existing persistence classes (inthis case: ProductService).


  Sample 9: Data Visualization  Run the sample :    Code walkthrough:Open the following files in a code editor:
  • sample9\Dashboard.mxml
Flex provides and extensive library of charting components such asLineChart and PieChart used in this example. Other charting componentsinclude ColumnChart, BarChart, AreaChart, BubbleChart,CandlestickChart, PlotChart, HLOCChart.
Flex charting components work like  the other data aware components: you use the dataProvider property to bind a chart to data.
Because they leverage vector graphics, charting components can beredrawn and animated at the client-side, helping the end-user to betterunderstand data trends and transitions.
Additional resources:
  
  Sample 10: Rich Media  Run the sample:      Code walkthrough:  Open the following files in a code editor:
  
  • sample10\SampleMedia.mxml
  • sample10\questions.mxml
  HTTPService is used to retrieve an XML document that contains the list of questions, video links, and cuepoints.
  The source attribute of the VideoDisplaycomponent is bound to the selectedItem in the List, so that the "answervideo" automatically starts palying when a question is clicked.
  Thecuepoint event is used on VideoDisplay to synchronize the captions (thecaptions are not part of the video, but where read from the XMLdocument).
  Also notice how the resizeEffect is used on the Panel component, to animate the panel when it is resized.
  Finallythe applications has two view states: the default state and the"videoPlaying" state. View states allow you to declaratively (usingMXML) represent different states of the applications. In this simplecase, the Panel is expanded in the videoPlaying state to reveal theVideoDisplay component.
  

  
  Appendix A: Data Access and Rendering Performance  To test data retrieval and rendering: To test client-side sorting:
  • Specify 20000  rows
  • Click "Get Data"
  • Click on a column header to sort 20000 rows at the client-side
Code walkthrough:Open the following files in a code editor:
  • sample11\Perf.mxml
  • WEB-INF\src\flex\testdrive\census\CensusService.java
  • WEB-INF\flex\remoting-config.xml
At the client-side, we use RemoteObject to remotely invoke thegetItems method on the CensusService class deployed in the applicationserver. The CensusService class accesses the embedded HSQLDB databaseand returns the number of rows requested. Using RemoteObject, the datais transferred in a binary format over HTTP.


  
  Appendix B: Creating Custom UI Components  Run the sample:      Code walkthrough:Open the following files in a code editor:
  • sample12\Store.mxml
  • sample12\AnimatedTileList.as
Although many Flex applications are built entirely using the UIcomponents available in the Flex framework, you can create custom UIcomponents by extending classes in the Flex framework.AnimatedTileList.as provides an example of a class that extends Canvasto provide an animated version of the TileList component.


  
  Summary and Next StepsThis test-drive has provided you with a first experience of Flex,primarily focused on Java integration. However, we have just scratchedthe surface, and there are many other online resources focusing on thedifferent aspects of the product. is a great place to start to become familiar with these resources. Thedeveloper experience is an important aspect of Flex. So also make sureyou download FlexBuilder to start building your own Flex projects.
Don‘t hesitate to send me your questions/comments on this test-driveand any suggestion to improve it. Thanks! christophe at coenraets dotorg.



查看积分策略说明
附件
2006-11-16 17:29
阅读权限: 1  下载次数: 18
testdrive.part1.rar (1.91 MB)
 
2006-11-16 17:29
阅读权限: 1  下载次数: 15
testdrive.part2.rar (1.91 MB)
 
2006-11-16 17:29
阅读权限: 1  下载次数: 16
testdrive.part3.rar (1.91 MB)
 
2006-11-16 17:29
阅读权限: 1  下载次数: 16
testdrive.part4.rar (1.91 MB)
 
2006-11-16 17:32
阅读权限: 1  下载次数: 15
testdrive.part5.rar (1.91 MB)
 
2006-11-16 17:32
阅读权限: 1  下载次数: 18
testdrive.part6.rar (1.91 MB)
 
2006-11-16 17:32
阅读权限: 1  下载次数: 14
testdrive.part7.rar (1.91 MB)
 
2006-11-16 17:32
阅读权限: 1  下载次数: 16
testdrive.part8.rar (419.73 KB)
 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多