flex与java通信可以使用HTTPService、RemoteObject。
HTTPService也可以有多种做法,text、xml、json等。
最简单的例子真接返回text:
flex_java.mxml
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" viewSourceURL="srcview/index.html"> <mx:HTTPService id="service" url="http://localhost:8888/flex_server/servlet/GetData" result="serviceRequest(event)" method="GET" > <mx:request xmlns=""> <name> {n.text} </name> </mx:request> </mx:HTTPService> <mx:Script> <![CDATA[ //当 HTTPService 调用成功返回时调度 private function serviceRequest(event:Event):void{ r.text=service.lastResult.toString(); } private function send():void{ //发送请求 service.send(); } ]]> </mx:Script> <mx:Label text="姓名:" x="275" y="55" fontSize="16" fontWeight="bold"/> <mx:TextInput id="n" x="367" y="58"/> <mx:TextArea id="r" x="275" y="123" height="149" width="252" editable="false" fontSize="16" textAlign="center"/> <mx:Label x="275" y="91" text="简介:" fontSize="16" fontWeight="bold"/> <mx:Button x="367" y="94" label="查询" width="160" fontSize="15" fontWeight="bold" height="23" click="send()"/> </mx:Application>
以get方式发送请求,request标签内是参数。
GetData.java
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class GetData extends HttpServlet { public GetData() { super(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name=request.getParameter("name"); response.setContentType("text/xml"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter() ; if(name!=null&&!"".equals(name)){ if(name.equals("gao")){ out.print("这是个好人呀!"); }else if(name.equals("wang")){ out.print("坏人,很坏的人,不是人!"); }else{ out.print("外星人!!"); } } out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public void init() throws ServletException { } }
以json返回方式:
java端用json生成类的json字符串,发送到flex客户端,flex再解析json为flex的类,这要使用到java的json包和flex的json包,我用的是json-lib-2.2.2-jdk15.jar和as3corelib.swc。
login.mxml:
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:HTTPService id="form" result="returnResult(event)" resultFormat="text" url="http://localhost:8888/flex_server/LoginServlet"> <mx:request xmlns=""> <name> {n.text} </name> <psw> {p.text} </psw> </mx:request> </mx:HTTPService> <mx:Script> <![CDATA[ import com.adobe.serialization.json.JSON; import mx.rpc.events.ResultEvent; private function returnResult(event:ResultEvent):void{ var person:Object=JSON.decode(event.result.toString()); t.text+=person.name; t.text+=person.age; t.text+=person.sex; } private function logins():void{ form.send(); } ]]> </mx:Script> <mx:TextArea id="t" height="124" width="336" x="297" y="242"/> <mx:Form width="336" height="167" x="297" y="44" borderStyle="outset" borderColor="#9263BD" backgroundColor="#9192AC" backgroundAlpha="0.86"> <mx:FormItem label="用户名:" fontSize="12" > <mx:TextInput id="n"/> </mx:FormItem> <mx:FormItem label="密码:" fontSize="12" > <mx:TextInput id="p"/> </mx:FormItem> <mx:Button label="登录" click="logins()"/> </mx:Form> </mx:Application>
package servlet; import gjs.Person; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; public class LoginServlet extends HttpServlet { public LoginServlet() { super(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); String name=request.getParameter("name"); String psw=request.getParameter("psw"); if("gjs".equals(name)&&"520".equals(psw)){ Person p=new Person("王八蛋",22,false); JSONObject jo=JSONObject.fromObject(p); out.print(jo.toString()); System.out.println(jo.toString()); }else{ out.print(""); } out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public void init() throws ServletException { // Put your code here } }
跟前面没什么两样,只是用json转了一下,都是按json接口来的,所以使用起来平台差异都不大。
传xml方式:
Servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); StringBuilder sb=new StringBuilder(); sb.append("<agents>"); sb.append("<agent id='100' name='大西瓜' age='21' sex='false'/>"); sb.append("<agent id='101' name='小西瓜' age='23' sex='true'/>"); sb.append("<agent id='102' name='烂西瓜' age='24' sex='false'/>"); sb.append("<agent id='103' name='无子西瓜' age='25' sex='true'/>"); sb.append("<agent id='104' name='打西瓜' age='27' sex='false'/>"); sb.append("</agents>"); out.write(sb.toString()); }
mxml:
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"> <mx:HTTPService id="h" resultFormat="object" url="http://localhost:8888/Flex/AgentServlet" result="getResult(event)" /> <mx:Panel label="Agent List"> <mx:DataGrid dataProvider="{l}" id="dg" width="100%" height="100%"> <mx:columns> <mx:Array> <mx:DataGridColumn headerText="id" dataField="id" /> <mx:DataGridColumn headerText="name" dataField="name" /> <mx:DataGridColumn headerText="age" dataField="age" /> <mx:DataGridColumn headerText="sex" dataField="sex" /> </mx:Array> </mx:columns> </mx:DataGrid> </mx:Panel> <mx:Script> <![CDATA[ import mx.events.DataGridEvent; import mx.events.ListEvent; import mx.events.ItemClickEvent; import mx.collections.ArrayCollection; import mx.rpc.events.ResultEvent; [Bindable] private var l:ArrayCollection; private var index:int; private function getResult(e:ResultEvent):void{ l=e.result.agents.agent as ArrayCollection; trace(e.result); } private function send():void{ h.send(); } ]]> </mx:Script> <mx:Button click="send()" label="Show Agents" x="420" y="324"/> </mx:Application>
RemoteObject方式:
先要安装lcds,在remoting-config.xml中加这个
<destination id="agentJavaObj"> <properties> <source>gjs.Agent</source> <scope>application</scope> </properties> </destination>
Flex.mxml:
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"> <mx:RemoteObject id="r" destination="agentJavaObj" /> <mx:Panel label="Agent List"> <mx:DataGrid dataProvider="{l}" id="dg" width="100%" height="100%" itemClick="addSub(event)"> <mx:columns> <mx:Array> <mx:DataGridColumn headerText="id" dataField="id" /> <mx:DataGridColumn headerText="name" dataField="name" /> <mx:DataGridColumn headerText="age" dataField="age" /> <mx:DataGridColumn headerText="sex" dataField="sex" /> </mx:Array> </mx:columns> </mx:DataGrid> </mx:Panel> <mx:Script> <![CDATA[ import mx.events.DataGridEvent; import mx.events.ListEvent; import mx.events.ItemClickEvent; import mx.collections.ArrayCollection; import mx.rpc.events.ResultEvent; [Bindable] private var l:ArrayCollection; private var index:int; private function callJava():void{ r.getAgent(); //服务成功返回后调用 r.addEventListener(ResultEvent.RESULT,showJavaObj); } private function addSub(e:ListEvent):void{ index=e.rowIndex; r.addAgent(e.rowIndex); r.addEventListener(ResultEvent.RESULT,addAgent); //去除之前的事件监听showJavaObj否则还会调用 r.removeEventListener(ResultEvent.RESULT,showJavaObj); } private function addAgent(e:ResultEvent):void{ var o:Object=e.result as Object; //加入子元素 l.addItemAt(o,index+1); } private function showJavaObj(event:ResultEvent):void{ l=event.result as ArrayCollection; } ]]> </mx:Script> <mx:Button click="callJava()" label="Show Agents" x="420" y="324"/> </mx:Application>
Agent.java:
package gjs; import java.util.ArrayList; import java.util.List; public class Agent { private long id; private String name; private int age; private boolean sex; //一定要有无参构造,因为写了有参构造没有默认的无参了 public Agent(){ } public Agent(long id,String name,int age,boolean sex){ this.id=id; this.name=name; this.age=age; this.sex=sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isSex() { return sex; } public void setSex(boolean sex) { this.sex = sex; } public long getId() { return id; } public void setId(long id) { this.id = id; } public List<Agent> getAgent(){ Agent a1=new Agent(100,"王八蛋",23,false); Agent a2=new Agent(101,"王九蛋",22,true); Agent a3=new Agent(102,"王十蛋",21,false); Agent a4=new Agent(103,"王七蛋",20,true); List<Agent> l=new ArrayList<Agent>(); l.add(a1); l.add(a2); l.add(a3); l.add(a4); return l; } public Agent addAgent(long id){ System.out.println(id); Agent a1=new Agent(200,"朱重八",33,true); return a1; } }
环境配置有点麻烦,可以参考“Flex + LCDS + Java 入门教程”这个文档。