Flex RemoteObject(转载)

来源:互联网 发布:c语言rand是什么意思 编辑:程序博客网 时间:2024/05/27 00:43

 Flex支持多种与服务器端的通讯方式,包括remote和socket等高级数据通讯方式。 remote采用amf(action message format)协议。amt是一种二进制格式,专用于as和服务器端通讯,比http通讯要快很多,而且支持多种数据类型,如java,.net,php等。本文将介绍如何使用Flex RemoteObject components调用服务器端java对象的方法。

Flex客户端使用RemoteObject

在mxml中声明一个id为ro的RemoteObject,在as中可以通过ro引用RemoteObject对象,destination是服务器端暴露的java 服务对象,Method的name是java服务对象中的方法,result是访问服务器方法的回调函数。本例中是使用RemoteObject访问服务器端HelloWorld的sayHello方法。

testHelloWorld.mxml代码:

<?xml version=”1.0″ encoding=”utf-8″?> <mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”> <mx:Script> <![CDATA[ import mx.controls.Alert; import mx.rpc.events.ResultEvent; [Bindable] private var memberResult:Object; private function say():void{ var user:User=new User(); user.setName(n.text); user.setId(”testId”); ro.sayHello(user); }public function handleResult(event:ResultEvent):void { target.text=event.result as String; } ]]> </mx:Script> <mx:RemoteObject id=”ro” destination=”HelloWorld”><mx:method name=” sayHello ” result=” handleResult (event)”/><mx:RemoteObject> <mx:TextInput id=”n” change=”say()”/> <mx:Label id=”target”/> </mx:Application>User.as代码package { [RemoteClass(alias="cn.com. remote.test.User")]public class User { public var name:String; public var id:String; public function getName():String{ return name; } public function setName(name:String ):void { this.name = name;} public function getId():String { return id; } public function setId(id:String):void { this.id = id; } }}


 

定义服务器端java对象

HelloWorld.java代码

package cn.com. remote.test;public class HelloWorld { public String sayHello(String name){System.out.println(”**********sayHello(String name) in*************”); System.out.println(”hello,”+name);return “hello,”+name; } public User getUser(String name){ System.out.println(”**********getUser in*************”); return new User(name,name+”Id”); } }


User.java代码

package cn.com. remote.test; public class User { private String name; private String id; public String getName() { return name; } public void setName(String name) { this.name = name; }public String getId() { return id; }public void setId(String id) { this.id = id; }}

配置服务器端destination

使用RemoteObject与服务器端通讯,需要用到Flex Date Services,本文使用的是BlazeDS server,BlazeDS的使用本文不做详细说明,可参看http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/

在remoting-config.xml中配置destination,增加如下代码

<destination id=“helloWorld “><properties><source>cn.com. remote.test .helloWorld </source><factory>springFactory</factory></properties></destination>

As对象与java对象的转换

在as中调用ro.sayHello时,传入一个as对象user,服务器端将会把user对象转换为java对象user。同样,如果服务器端方法return的是java User对象,as接收到的将是as的User对象。[RemoteClass(alias="cn.com. remote.test.User")]声明了As user对象与java User对象的对应关系。下面是基础类型或常用类的对应关系图。

需要注意到问题

flex remote传递object参数和接受返回的dojo对象,应注意以下问题: 

1.as对象属性必须为public的 

2.remote调用的java方法时,参数不能作为区别不同方法的依据,也就是说,java方法不 

能重名 

3.dojo对象,必须有无参构造函数 

4.as对象需加[RemoteClass(alias="cn.com. remote.test.User")] 

原创粉丝点击