flex的remoteobject方式调用java的方法

今天摸索了一下Flex3中使用RemoteObject和Java类的通讯问题,感觉非常方便,虽然使用HttpService也可以,但多了一个控制器,并且还要对数据进行处理;而使用RemoteObject,则可能直接访问类方法。

看步骤:
第一步:为了测试Flex对复杂类型List的支持,所以我写了一个方法用于返回元素类型为Student的List。先看Student类代码:
package com.aptech.flex;
public class Student
{
private int sid;
private String sname;
public Student(int sid, String sname){
this.sid = sid;
this.sname = sname;
}
public Student(){
}
public int getSid(){
return this.sid;
}
public String getSname(){
return this.sname;
}
public void setSid(int sid){
this.sid = sid;
}
public void setSname(String sname){
this.sname = sname;
}
}

第二步:创建示意性的业务方法,返回List<Student>集合,习惯使用泛型,如果不用泛型应该也能处理。
[code="javpackage com.aptech.flex;
import java.util.*;
public class HelloWorld
{
public String sayHello(String str){
return str + "你好";
}
public List<Student> strList(){
List<Student> list = new ArrayList<Student>();
list.add(new Student(1, "张三"));
list.add(new Student(2, "李四"));
list.add(new Student(3, "王五"));
return list;
}
}a"]

第三步:修改<Tomcat>/lcds/flex/remoting-config.xml配置文件,添加如下语句:
<destination id = "hw">
<properties>
<source>com.aptech.flex.HelloWorld</source>
<scope>application</scope>
</properties>
</destination>

在该文件中,貌似不能写中文注释,启动容器时出现异常。
第四步:创建Flex工程,定义<mx:RemoteObject />,内容如下
<mx:RemoteObject id="hwro" destination="hw"endpoint="http://localhost:8080/Flex_J2ee/messagebroker/amf"></mx:RemoteObject>

这里的destination必须和第三步的<destination id = "hw">一致。但是在此句中我并不明白为什么要加上endpoint这个属性才有用,希望高手能帮我解释一下。
第五步:定义一个按钮,并触发单击事件。
<mx:Button x="123" y="154" label="访问java类" click="doJava(event)"/>
doJava事件定义如下:
internal  doJava(event: Event): void{
hwro.strList();
hwro.addEventListener(ResultEvent.RESULT, onCallback);
}

以下是结果处理方法:
private  onCallback(event: ResultEvent): void{
var ac: ArrayCollection = event.result as ArrayCollection;
var arr: Array = ac.toArray();
var str: String = "";
for(var a in arr){
str += arr[a].sid + "," + arr[a].sname + ""n";
}
Alert.show(str);
}

Flex将Java类的List自动转换成了ArrayCollection类型,该示例中List元素类型为Student,则可以使用E.属性来访问。

你可能感兴趣的:(Flex)