Flex uses the RemoteObject component __flex

Source: Internet
Author: User
Tags cdata class definition reserved serialization zend zend framework
Sample RemoteObject Application

Calling the RemoteObject component in ActionScript

Accessing Java objects in the source path

accessing EJBs and other objects in JNDI

Reserved method Name

Serialization between ActionScript and Java

Using custom serialization

You can use the Flex RemoteObject component to invoke methods for ColdFusion components or Java classes.

You can also use RemoteObject components that contain PHP and. NET objects in conjunction with Third-party software, such as open source project amfphp and SABREAMF, and midnight coders Weborb. For more information, please visit the following Web site:

Zend Framework http://framework.zend.com/

amfphp http://amfphp.sourceforge.net/

SABREAMF HTTP://WWW.OSFLASH.ORG/SABREAMF

Midnight Coders Weborb http://www.themidnightcoders.com/

The RemoteObject component uses the AMF protocol to send and receive data, while the WebService and Httpservice components use the HTTP protocol. AMF is significantly faster than HTTP, but server-side coding and configuration are often more complex.

As with the Httpservice and WebService components, you can use the RemoteObject component to display database query results in your application. You can also use this component to insert, update, and delete data in the database. After you return the query results to your application, you can display them in one or more user interface controls.

For API reference information on the RemoteObject component, see Mx.rpc.remoting.mxml.RemoteObject. Sample RemoteObject application MXML Code

The application in the following example uses the RemoteObject component to invoke the ColdFusion component. The ColdFusion component queries a MySQL database table named users. It returns the query results to the application in which the query results are bound to the Dataprovider property of the DataGrid control and displayed in the DataGrid control. The application also sends the user name and e-mail address of the new user to the ColdFusion component, and the ColdFusion component performs the insert operation in the User database table.

<?xml version= "1.0" encoding= "Utf-8"?> <s:application xmlns:fx= "http://ns.adobe.com/mxml/2009" xmlns:s= 
    "Library://ns.adobe.com/flex/spark" xmlns:mx= "library://ns.adobe.com/flex/mx" minwidth= "955" minHeight= ">" <fx:Declarations> <mx:remoteobject id= "userrequest" destination= "Coldfusi On "source=" Flexapp.returnusers "> <mx:method name=" returnrecords "result=" re Turnhandler (event) "fault=" Mx.controls.Alert.show (event.fault.faultString) "/> < Mx:method name= "Insertrecord" result= "Inserthandler ()" fault= "Mx.controls.Alert.show (event.fault.f aultstring) "/> </mx:RemoteObject> </fx:Declarations> <fx:Script> &l t;! 
             
            [cdata[import mx.rpc.events.ResultEvent;  
        Private Function Returnhandler (e:resultevent): void    {dguserrequest.dataprovider = E.result; 
            Private Function Inserthandler (): void {userrequest.returnrecords (); Private Function ClickHandler (): void {Userrequest.insertrecord (usern 
            Ame.text, Emailaddress.text); ]]> </fx:Script> <mx:form x= "y=" width= "> &LT;MX:FORMITEM&G" 
            T 
        <s:label text= "Username"/> <s:textinput id= "Username"/> </mx:FormItem> <mx:FormItem> <s:label text= "Email address"/> <s:textinput id= "Emailaddre ss "/> </mx:FormItem> <s:button label=" Submit "click=" ClickHandler () "/> </mx:form& 
 
    Gt <mx:datagrid id= "Dguserrequest" x= "y=" > <mx:columns> <mx:datagridcolumn Heade Rtext= "User ID" datafield= "userid"/> <mx:datagridcolumn headertext= "user Name" datafield= "username"/> </mx:columns> </mx:DataGrid> </s:Application>

In this application, the destination property of the RemoteObject component is set to the Coldfusion,source property set to the fully qualified name of the Coldfusion component.

Conversely, when using LiveCycle Data services ES or blazeds, you need to specify the fully qualified class name for the source property of the remote service target in the configuration file (remoting-config.xml file by default) and The name of the target specified in the destination property of the RemoteObject component. The target class must also have a constructor with no arguments. When using ColdFusion, you can choose to configure the target in this way instead of using the RemoteObject component's Source property. ColdFusion Components

The application calls the ColdFusion component below. This ColdFusion code executes SQL database inserts and queries and returns the results of the query to the application. ColdFusion pages use the cfquery tag to insert data into the database and query the database, using the Cfreturn tag to format the query results to ColdFusion query objects.

<cfcomponent name= "Returnusers" > <cffunction name= "returnrecords" access= "remote" returntype= "Query" > <cfquery name= "Alluserinfo" datasource= "FLEXCF" > SELECT userid, username, EmailAddress FRO M users </cfquery> <cfreturn alluserinfo> </cffunction> <cffunction name= "Insertrecord" access= "remote" returntype= "void" > <cfargument name= "username" true "required=" type= G "> <cfargument name=" EmailAddress "required=" true "type=" string "> <cfquery name=" addempinfo "Datasource=" FLEXCF > INSERT into Users (username, emailaddress) VALUES (<cfqueryparam V Alue= "#arguments. username#" cfsqltype= "Cf_sql_varchar" maxlength= "255", <cfqueryparam value= "#argument 
    s.emailaddress# "cfsqltype=" Cf_sql_varchar "maxlength=" 255 ">) </cfquery> <cfreturn> </cffunction>     
</cfcomponent> 
calling the RemoteObject component in ActionScript

In the following ActionScript example, the Useremoteobject () method is invoked to declare the service, set the target, set result and fault event listeners, and invoke the GetList () method of the service.

<?xml version= "1.0"?> <!--fds\rpc\roinas.mxml--> <s:application xmlns:fx= "http://ns.adobe.com/mxml/ 2009 "xmlns:s=" Library://ns.adobe.com/flex/spark "xmlns:mx=" Library://ns.adobe.com/flex/mx "minWidth=" 95 5 "minheight=" > <fx:Script> <! 
            [cdata[import Mx.controls.Alert; 
            Import Mx.rpc.remoting.RemoteObject; 
            Import mx.rpc.events.ResultEvent; 
 
            Import mx.rpc.events.FaultEvent;          
            [bindable] public var emplist:object; 
 
            public Var Employeero:remoteobject; 
                Public Function Useremoteobject (Intarg:int, strarg:string): void {Employeero = new remoteobject (); 
                Employeero.destination = "Salarymanager"; 
                EmployeeRO.getList.addEventListener ("result", Getlistresulthandler); 
                Employeero.addeventlistener ("Fault", Faulthandler); Employeero.getlist (DEPTCOmboBox.selectedItem.data); 
                Public Function Getlistresulthandler (event:resultevent): void {//do something 
            Emplist=event.result; } Public Function Faulthandler (event:faultevent): void {//Deal with event.fault.faultString 
                , etc. 
            Alert.show (event.fault.faultString, ' Error '); }]]> </fx:Script> <s:combobox id= "Deptcombobox"/> </mx:Application>
accessing Java objects in the source path

Use the RemoteObject component to access stateless and stateful Java objects located in the source path of the LiveCycle Data Services ES, blazeds, or ColdFusion Web applications. Separate class files can be placed in the web‑inf/classes directory of the WEB application to add them to the source path. You can place classes contained in a Java Archive (JAR) file in the Web‑inf/lib directory of your WEB application to add them to the source path. In the LiveCycle Data services ES, blazeds, or ColdFusion services-config.xml files, or by reference to files (such as remoting-config.xml files), in the remote service eye The fully qualified class name is specified in the Source property of the header. The class must also have a constructor with no arguments. For ColdFusion, you can choose to set the RemoteObject component's destination property to ColdFusion and set the Source property to the fully qualified name of the ColdFusion component or Java class.

When you configure a remote service target to access a stateless object (Request scope), Flex creates a new object for each method call, rather than calling multiple methods on the same object. You can set the scope of an object to the request scope (the default), the application scope, or the session scope. An object in an application scope can be used by a WEB application that contains the object. An object in a session scope can be used for an entire client session.

When you configure a remote object target to access a stateful object, Flex creates the object once on the server and maintains the state of the object between the method calls. If storing objects in an application scope or session scope can cause memory problems, you should use the request scope. accessing EJBs and other objects in JNDI

You can access the Enterprise JavaBeans (EJB) and other objects stored in Java naming and directory Interfaces (JNDI) by invoking the method on the target, which is the service façade class that looks up an object in Jndi and invokes its methods.

You can use stateless or stateful objects to invoke Enterprise JavaBeans and other methods that use JNDI objects. For EJBS, you can invoke the service façade class, which returns an EJB object in JNDI and invokes a method on that EJB.

In the Java class, you can use the standard Java encoding pattern, in which you can create an initial context and perform a JNDI lookup. For EJBS, you can also use the standard encoding mode, where you can create a class that contains the Create () method that invokes the EJB main object and the business method of the resulting EJB.

The following example uses a method named Gethellodata () in the façade class definition:

<mx:remoteobject id= "Hello" destination= "Rodest" > 
    <mx:method name= "Gethellodata"/> </mx 
: Remoteobject>

On the Java side, the Gethellodata ()   method encapsulates all the content necessary to invoke the business method for EJB. The Java method in the following example does the following:

Creates a new initial context for invoking the EJB

To perform a JNDI lookup that gets the EJB main object

Invoke the EJB main object's  create () &nbs P; method

Invokes the EJB's  sayhello ()   method

 ... public void Gethellodata () {try{InitialContext ctx = new InitialContext (); 
        Object obj = ctx.lookup ("/hello"); 
        Hellohome ejbhome = (hellohome) portableremoteobject.narrow (obj, hellohome.class); 
        Helloobject ejbobject = Ejbhome.create (); 
        String message = Ejbobject.sayhello (); 
    catch (Exception e); } 
...
Reserved Method name

The Flex remote Library uses the following method name, and do not use these names for your own methods:

AddHeader () 
AddProperty () Deleteheader () hasOwnProperty () 
ispropertyenumerable 
() isPrototypeOf () 
registerclass () 
tolocalestring () 
toString () 
unwatch () 
valueof 
() Watch ()

Also, the following underscore (_) character should not be used as the beginning of the method name.

Typically, you simply name the RemoteObject method (action) by service variables to make them accessible. However, if the operation name happens to be the same as the method defined for the service, a naming conflict occurs. You can use the following ActionScript methods for the RemoteObject component to return the action for the given name:

Public Function Getoperation (name:string): Operation
serialization between ActionScript and Java

LiveCycle data Services ES and BlazeDS serialize ActionScript (AMF 3) and Java and the ColdFusion data types in two directions. For information about ColdFusion data types, see the ColdFusion documentation set. convert data from ActionScript to Java

When a method parameter sends data from an application to a Java object, the data is automatically converted from the ActionScript data type to the Java data type. When LiveCycle Data Services ES or blazeds searches for a suitable method for a Java object, it further uses a looser conversion to find a match.

Simple data types (such as Boolean and String values) on the client typically match exactly the remote APIs. However, Flex tries some simple transformations when searching for appropriate methods for Java objects.

ActionScript Array can be indexed in two ways. All indexes in a strict Array are of type number. At least one index in an associative Array is based on a String type. Be sure to understand the type of array sent to the server because the array type changes the data type of the parameter that is used to invoke the method on the Java object. All numeric indices in a dense Array are contiguous (that is, no interval), starting with 0 (0). There is an interval between numeric indices of sparse arrays; This Array is processed as objects, and numeric indexes become properties that are serialized as JAVA.UTIL.MAP objects to avoid sending many empty entries.

The following table lists the ActionScript (AMF 3) to Java transformations supported for simple data types.

Boolean, Boolean, and String

td>

ActionScript type (AMF 3)

Deserialize to Java

Supported Java type bindings

Array (dense)

java.util.List

java.util.collection,  Object[] (native array)

If the type is an interface, it is mapped to the following interface implementation:

List to ArrayList

SortedSet to TreeSet

Set to has A new instance of the Hset

Collection to ArrayList

Custom Collection implementation is bound to that type.

Array (sparse)

Java.util.Map

Java.util.Map

Boolean

String "true" or "false"

Java.lang.Boolean

Flash.utils.ByteArray

Byte []

 

flash.utils.IExternalizable

Java.i O.externalizable

 

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.