Flex与Java通信之HttpService方式

合集下载

Fle与数据库的连接方式

Fle与数据库的连接方式

Flex连接数据库的3种方式首先,做一点说明。

Flex是不能直接连接数据库的,这一点大家需要知道,它只能间接地连接数据库。

Flex 中提供了三种方式:HttpService,WebService 和RemoteObject。

其中HttpService可以直接获取XML中的数据,还可以通过JSP,ASP以及PHP读取数据库中的数据,这个比较简单,而且网上也有很多例子,我就不多说了。

WebService我不懂,请自己查资料。

我一直用的是JAVA对象连接数据库,感觉这个挺方便,而且J2EE的技术已经很成熟。

今天的教程就是以 Flex + JAVA + SQLServer获取数据库公告信息为例简单说一下RemoteObject的用法。

前提1.确保你安装了Flex Data Service。

这个对于单个CUP无限APP是免费的,可以去Adobe下载。

如果只是读取XML文件是不需要这个的,连接数据库就需要它了。

2.安装了Flex Builder或者有Flex SDK。

我这里使用的是Flex Builder(IDE就是方便啊 ^_^)。

3.安装了SQLServer数据库。

4.安装了JRUN或者tomcat或其它的J2EE容器,因为发布的时候我们的程序要运行在J2EE平台上。

5.安装了JDK。

第一步:创建数据库这里我们有一个公告表,表名为Bulletin。

结构如下:字段名称字段类型说明ID自动编号自动编号title Nvarchar(100)题目date datatime日期author Nvarchar(20)作者content ntext内容在数据库中创建这个表。

保存之后进入下一步。

第二步:在JAVA中编写获取公告的代码首先,我们要创建一个公告类来专门保存获取的公告信息,代码如下。

NoticeInfo.javapackage net.zhuoqun.connectDB;import java.util.Date;public class NoticeInfo {private String title; // 标题private String author; // 作者private String content;// 内容private Date dates; // 时间public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}……………… // 其它get 和 set 方法。

整合Flex和Java--配置篇

整合Flex和Java--配置篇

3、 将该工程发布到 tomcat 下,并启动 tomcat。 (注:一定要启动 tomcat,因为在后面 的设置中,它要验证工程的路径) 4、 然后在该工程上右键Flex Project NatureAdd Flex Project Nature
配置正确的显示
配置服务器路径
建议不要修改这里的配置
<mx:Script> <![CDATA[ import mx.rpc.events.ResultEvent; function gg(evnet:ResultEvent):void{ var ff:String = evnet.result as String; ggg.text = ff; } function remotingSayHello():void{ var sname:String = nameInput.text; h.hello(sname); } ]]> </mx:Script> <mx:RemoteObject destination="hello" id="h" result="gg(event)" endpoint="http://localhost:8080/flexweb/messagebroker/amf" > </mx:RemoteObject>
<listener-class>flex.messaging.HttpFlexSession</listener-class> </listener> <!-- MessageBroker Servlet --> <servlet> <servlet-name>MessageBrokerServlet</servlet-name> <display-name>MessageBrokerServlet</display-name> <servlet-class>flex.messaging.MessageBrokerServlet</servlet-class> <init-param> <param-name>services.configuration.file</param-name> <param-value>/WEB-INF/flex/services-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>MessageBrokerServlet</servlet-name> <url-pattern>/messagebroker/*</url-pattern> </servlet-mapping>

java webservice几种调用方式

java webservice几种调用方式

java webservice几种调用方式Java Web Service是一种流行的技术,用于通过网络在不同系统之间实现通讯和集成。

在Java中,有多种方式可以调用Web Service。

下面将介绍几种常用的调用方式。

1.使用SOAP(Simple Object Access Protocol)协议SOAP是一种基于XML的通讯协议,可以在网络上使用HTTP、SMTP等协议发送和接收消息。

在Java中,可以使用SOAP协议调用Web Service。

SOAP使用WSDL(Web Services Description Language)来描述Web Service的接口和功能。

可以使用轻量级的SOAP框架Apache CXF或Metro来创建和调用SOAP Web Service。

调用方式主要包括以下几步:-创建一个Java类来表示Web Service的接口,并使用注解来定义接口的操作。

-使用工具,如Apache CXF或Metro,将该类生成WSDL文档。

-使用WSDL文档生成客户端代码,以便在调用Web Service时使用。

-创建一个客户端程序,通过调用生成的客户端代码来调用Web Service的方法。

2.使用JAX-WS(Java API for XML Web Services)标准JAX-WS是一种Java的Web Service规范,它提供了一种简单的方式来创建和调用Web Service。

JAX-WS提供了注解,用于将Java类转换为Web Service,并且可以使用Java的代理类来调用Web Service 的方法。

调用方式包括以下几步:-创建一个Java类,并用@WebService注解来标记它作为一个Web Service的实现。

-在该类中定义Web Service的操作,并使用@WebMethod注解来标记这些方法。

-使用工具,如JDK的wsimport命令或Eclipse的WebService工具来生成客户端代码。

偷菜类游戏FLEX

偷菜类游戏FLEX

哈尔滨师范大学学年论文题目基于FLEX的偷菜游戏设计学生刘子甲指导教师周国辉教授年级2008级专业数字媒体技术系别计算机系学院计算机信息与工程学院哈尔滨师范大学2010年 5论文提要近年来,随着计算机信息技术的告诉发展,人们物质文化的不断提高,一些偷菜养成类的网页游戏也开始走进我们的生活。

偷菜类游戏是基于FLEX体系,服务器一般用C/C++或JA V A来实现,前端用FLASH,AS3 来实现,并通过链接数据库,从而制作出丰富多彩的偷菜类游戏。

由于每台电脑都安装了FLASH PLAYER的相应版本,因此通过这种体系制作的游戏可以不用安装第三方插件,方便用户,也节省了开发所需的成本。

对于偷菜游戏的设计,主要是主界面、土地、工具栏、好友数据几方面来设计,然后再把相应模块添加进来,进行相应的调试,最终形成可供娱乐的偷菜游戏。

关于偷菜类游戏设计的几个问题刘子甲摘要:随着编程语言种类的不断发展,应用软件的不断增多,选择合适的编程工具来完成相应的目的会很大程度上成为减少成本、提高效率。

对于富互联网时代的来临,选择FLEX来制作偷菜类游戏成为了网页游戏编程人员不二的选择。

对于一些制作方面的技术问题,需要我们不断的探索和改进。

关键词:FLEX偷菜类游戏富互联网近年来,伴随着富互联网时代的来临,网页游戏也逐渐成为了游戏中一个不可替代的角色,人人网的开心农场、腾讯的QQ农场以及一些相关类型的游戏如雨后春笋般出现。

这使我们不得不对该类游戏的相关技术进行探索,从中总节和改进相关的技术环节,来达到熟练掌握该类游戏的制作流程,充实自己的编程经验和能力的目的。

一、为什么要选择FLEX体系来制作偷菜类游戏?FLEX是ria技术的主要倡导者macromedia公司于2004年发布,是为了满足ria企业级开发而推出的表示层服务器和应用层框架。

主要采用mxml界面语言和actionscript脚本语言。

FLEX的出现开启了ria(rich internet application)富互联网应用的时代。

myflex笔记

myflex笔记

Flex原理1.事件的原理分为三个阶段:捕获、目标、冒泡事件的起源是跟结点stage 直到发生事件的对象,之后又向相反的方向回到stageStage->obj :捕获阶段寻找obj的过程:目标阶段Obj->stage:冒泡阶段节点:stage->application-> 容器(panel等)->obj;2. data 绑定原理[Bindable(event="propertyChange")]。

(默认的绑定)Flex组件默认监听了propertyChange 事件;3. flex通信原理:3.1过程:通道-》端点-》消息-》服务-》目的地-》适配器3.2 通信的组件:. RemoteObject –远程调用• HTTPService –http代理• WebService –http代理• Producer –消息• Consumer –消息3.3 原理BlazeDS :是一个基于服务器的Java远程调用(remoting)和Web消息传递(messaging)技术图解:3.1端点(Endpoint) (在MessageBrokerServlet中实现)。

endpoint,其默认形式是/messagebroker/amf通道类型:amf Channel(速度快)、httpChannel(二进制无压缩的)等消息通过channel传到endPoint ,Channel 和endpoint的编码格式必须一致比如都用amf的3.2. messgeBroker(消息代理人)messgeBroker 将消息根据(destination)服务请求的种类,传给不同的服务,服务再传到对应的服务的destination3.3.Service and destination 类别remoteService->remoteServiceDestination(RomoteObject 对象)->remote-config.xmlhttpproxyService->httpproxyserviceDestination(httpService\webService 对象)->proxy-config.xmlmessageservice->messageDestination(producer\consumer 对象)->message-config.xmldestination:目标其实是一个请求的目标:对于常用的远程方法调用来说,其目标(destination)就是某个特定的java服务,或者某个特定的配置好的Java类对于代理目标来说,则是定义好的代理种类,比如说普通HTTP代理还是基于WebService的代理对于消息目标来说,则是某个特定的消息服务种类3.4.AdapterRemote->javaadapterProxy->httproxyAdaper\soapadaperMessage->jms or as(客户端交换信息)4. flex 配置Flex socket 通信1.DataGrid1.dataGrid 数据的处理itemClick 事件:event:ListEvent;(var grid:DataGrid= event.target as DataGrid)所点击列的表头:grid.columns[event.columnIndex].headerText;列索引:event.columnIndex;行索引:event.rowIndex;选中的行数据:grid.selectedItem选中的单元格数据:grid.selectedItem[grid.columns[e.columnIndex].dataFiled]2. DataGrid 数据的移动方法:grid.removeItemAt;grid.addItemAt;3. Mxml中引入xml文件(利用HTTPService)可以作为dataGrid的数据源实例:<mx:HTTPService id="simpletest"url="assets\photoFood.xml"result="photoColl=stResult.list.food"/>注意:private var photoColl:arrayCollection;或者用监听方式取回结果:Private function onResult(event:ResultEvent):void{This. photocell=event.result.list.food ;}photoFood.xml:<list><food><food_name>Artichoke Dip</food_name><photo>artichokeDip.jpg</photo></food><food><food_name>Bread Pudding</food_name><photo>breadPudding.jpg</photo></food><food><food_name>Cheesecake</food_name><photo>cheesecake.jpg</photo></food></list>4.dataGrid 的itemReader 可以是自定义的任何组件;rendererIsEditor="true" :渲染的组件可以编辑,并且编辑后的值可以返回到datagrideditorDataField="value"(默认为“text”):渲染器要编辑的属性5.ArrayCollection的过滤器:实例:利用combobox控制数据的显示private function myFilter():void{if(this.myCom.selectedItem.toString()=="ALL"){this.reviewList.filterFunction=null;}else{this.reviewList.filterFunction=myFunc;}//refresh() 必须添加的方法this.reviewList.refresh();}//过滤器的筛选规则返回值为boolean,参数为容器的一个对象private function myFunc(item:Object):Boolean{return(item.rating.toString()==this.myCom.selectedItem.toString());}<mx:ComboBox dataProvider="{}" change="myFilter()" id="myCom"/>Private var com:ArrayCollection=new ArrayCollection(["1","2","3","4","5","ALL"]);DataGrid颜色专题总结:1。

Flex介绍

Flex介绍
Flex
1 什么是Flex
Flex是一个针对企业级富互联网应用的表示层解 决方案;
Flex是一种应用程序框架; Flex序列产品包括编译工具和IDE,通过编写
MXML(一种类XML标记语言)和ActionScript (AS,Flex的脚本语言,从Flash移植过来)代码, 用编译器来生成SWF文件,使用浏览器的Flash Player插件就可以进行观看。 几乎每一个用户浏览器都安装了Flash Player插件
3. Flex和Flash的比较
1 相同点
最终都生成SWF文件,通过Flash Player 来解释 运行。
2 产品市场定义的差异和针对不同的开发人 员
Flex是一直RIA解决方案,针对的是企业级的网 络应用(数据通信Flex表现得非常好)。
flash主要应用在平面动画、广告设计、移动应 用、多媒体应用等方面,同时也可以用于网络 应用开发。
2. Flex的特性
使用矢量图形
继承Flash的矢量图形表达能力。 矢量图形在放大时不失真,但运行较负责
的图形时,会消耗较多的CP改矢量图形。
丰富的组件库
使用组件,极大提高代码的重用性。 比Flash组件更多,运行小赖也有很大的改
进。 采用全新的架构,使得组件的样式定制和
外观修改更简单。 支持CSS 可以创建自己的组件
对多媒体的广泛支持
支持多媒体,比如FLV流媒体 可以对多媒体的播放进行动态控制 提供了与Flash Media Server(FMS)等其他
流媒体服务器进行通信的功能 可以在本地存储数据(本地共享对象)
与服务器端的通信
除了可以加载XML文件和其他文本资料,还可以 和ASP、JSP等多种服务器端程序通信,连接远程 WebService

Flex讲解

Flex讲解

Flex事件机制(二) 事件机制( 事件机制
Event类作为创建Event对象的基类,当发生事件时,Event对象将作为参数传递 给事件侦听器。如MouseEvent、KeyboardEvent • Event类有几个常用的公共属性: ◆是否冒泡:bubbles; ◆目标对象:target; ◆所处阶段:eventPhase; ◆当前对象:currentTarget; Flex事件机制中的自定义事件,也就是向监听器传递自己定义的事件类型,同 时可以通过事件传递参数。 • 1.创建自定义事件名称的Event dispatchEvent(newEvent(“myEvnet”,true,false)); • 2.创建自定义事件类 Public class MyEvent extends Event{ dispatchEvent是EventDispatcher的方法: publicfunctiondispatchEvent(event:Event):Boolean将事件调度到事件流中。事件 目标是对其调用dispatchEvent()方法的EventDispatcher对象。 •
控件简介(二)
• • • • • • • • • • • • • • • • • • • 5:flex控件: 警告alert弹出警告框 下拉列表combobox下拉数据列表 选色器colorpicker可选择的调色盘 数据表格datagrid 数据表格 日期选择器datechooser选择日期控件 日期条 datefield 单击弹出日期选择器 水平列表horizontalList 水平列表项目 水平尺/垂直尺 hrule vrule单个水平或垂直标尺 水平、垂直滑竿 hslider,vslider 图像 image 支持gif jpeg png svg swf 列表list 可滚动的数据组 计数器numericstepper单击向上的按钮增加数据,单击向下的按钮减少数据 进度条progressbar 当前操作进度 滚动条 水平,垂直滚动 scrllbar,hscrollbar,vscrollbar swf加载器 显示swf文件 列表条tabbar一组水平的列表 排列列表tilelist类似表格的行列对正排列的项目 树tree、以展开树的方式显示继承关系的数据 音像videodisplay flex应用中的数据流媒体

Flex向Java调用

Flex向Java调用

Flex向Java调用前几天由于搞项目需要用到Flex 向 Java 服务通信传输数据,搞了好大半天灰常痛苦,在网上的片段很少,现在我整合一下。

希望对以后要用到的童靴有一点用处。

我项目里面传输的是二进制数据。

Flex 向 Java servlet通信,Java服务端再返回数值到Flex客户端。

童鞋们先要下载Flex 的两个包(flex-messaging-common.jar,flex-messaging-core.jar)放置Java工程的lib下。

标签:Apache Flex JavaServlet代码片段(6)[文件] AllServlet.java ~ 3KB 下载(37)view sourceprint?package cn.tianqi.game.servlet;import java.io.DataOutputStream;import java.io.IOException;import java.util.Collection;import java.util.List;import java.util.Map;import java.util.zip.DeflaterOutputStream;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import cn.tianqi.game.action.util.AmfDataServlet;import cn.tianqi.game.action.util.Configuration;import cn.tianqi.game.action.view.MapBean;import cn.tianqi.game.action.view.ResourceBean;import cn.tianqi.game.action.view.SysBean;import cn.tianqi.game.action.vo.ResourceVo;import flex.messaging.io.SerializationContext;import flex.messaging.io.amf.Amf3Output;public class AllServlet extends HttpServlet {private static final long serialVersionUID = 1L;private AmfDataServlet amfData=new AmfDataServlet();private ResourceBean catBean=ResourceBean.getInstance();private MapBean mapBean=MapBean.getInstance();private SysBean sysBean=SysBean.getInstance();public AllServlet() {super();}public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}@SuppressWarnings("unchecked")public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=utf-8");Mapmap=(Map)amfData.getObj(request.getContentLength(), request.getInputStream());String method=String.valueOf(map.get("method"));if(method.equals(Configuration.SYS_INIT)){Collection coll=catBean.resourceCat().values();//所有素材资源数据Collection coll2=catBean.mapResource().values();//所有地图素材资源数据Collection coll3=mapBean.selectAllMap().values();//所有地图资源数据List<ResourceVo> coll4=catBean.selectALLRes();//所有资源表数据send(response, sysBean.sysInit(coll,coll2,coll3,coll4));}else if(method.equals(Configuration.CAT_RESOURCE)){send(response, catBean.resourceCat().values());}elseif(String.valueOf(map.get("method")).equals(Configuration.MAP _RESOURCE)){send(response, catBean.mapResource().values());}elseif(method.equals(Configuration.CAT_RESOURCE_ADD)){ Map cat=(Map)map.get("data");send(response, catBean.saveResourceCat(cat));}elseif(method.equals(Configuration.MAP_RESOURCE_DATA)){ send(response, mapBean.selectAllMap().values());}else if(method.equals(Configuration.MAP_DATA_SAVE)){Map mds=(Map)map.get("data");send(response, mapBean.saveMap(mds));}}protected void send(HttpServletResponse response,Object obj) throws IOException{Amf3Output amf3=new Amf3Output(new SerializationContext());DeflaterOutputStream stream = new DeflaterOutputStream(newDataOutputStream(response.getOutputStream()));amf3.setOutputStream(stream);amf3.writeObject(obj);stream.finish();}public void init() throws ServletException {// Put your code here}}[文件] AmfDataServlet.java ~ 2KB 下载(28)view sourceprint?package cn.tianqi.game.action.util;import java.io.ByteArrayInputStream;import java.io.DataInputStream;import java.io.IOException;import java.io.InputStream;import javax.servlet.ServletInputStream;import flex.messaging.io.SerializationContext;import flex.messaging.io.amf.Amf3Input;public class AmfDataServlet {/*** 解析HttpServletRequest上传的二进制数据* @param contentLength 上传的数据总长度(request.getContentLength())* @param stream 上传的数据(request.getInputStream())* @return Object*/public Object getObj(int contentLength, ServletInputStream stream) {Object obj = null;DataInputStream dis = new DataInputStream(stream);byte[] by = new byte[contentLength];try {int bytesRead = 0, totalBytesRead = 0;while (totalBytesRead < contentLength) {bytesRead = dis.read(by, totalBytesRead, contentLength);totalBytesRead += bytesRead;}Amf3Input amf = new Amf3Input(new SerializationContext()); InputStream is = new ByteArrayInputStream(by);amf.setInputStream(is);obj = amf.readObject();} catch (ClassNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return obj;}/*** 解析byte[]转成Object* @param bytes 数据* @return Object*/public Object getObj(byte[] bytes){Object obj=null;try {Amf3Input amf = new Amf3Input(new SerializationContext()); InputStream is = new ByteArrayInputStream(bytes);amf.setInputStream(is);obj=amf.readObject();} catch (ClassNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return obj;}}[文件] Servlet.as ~ 2KB 下载(24)view sourceprint?package cn.tianqi.game.servlet{import .URLLoader;import .URLLoaderDataFormat;import .URLRequest;import .URLRequestMethod;public class Servlet{private static var servlet:Servlet=null;private var httpUrl:String="http://192.168.1.101:8080/manager/";//private var httpUrl:String="http://localhost:8080/manager/";public function allServlet():URLRequest{var urlRequest:URLRequest=new URLRequest(httpUrl+"AllServlet");urlRequest.contentType = 'applicatoin/octet-stream';urlRequest.method=URLRequestMethod.POST;return urlRequest;}// public function resourceCatServlet():URLRequest // {// var urlRequest:URLRequest=new URLRequest(httpUrl+"CatInfoServlet");// urlRequest.contentType = "applicatoin/octet-stream";//urlRequest.method=URLRequestMethod.POST;// return urlRequest;// }public function fileUpload():URLRequest{var urlRequest:URLRequest=new URLRequest(httpUrl+"FileUpload");return urlRequest;}// public function saveResourceCat():URLRequest// {// var urlRequest:URLRequest=new URLRequest(httpUrl+"ResourceAddServlet");//urlRequest.method=URLRequestMethod.POST;// return urlRequest;// }// public function mapResource():URLRequest// {// var urlRequest:URLRequest=new URLRequest(httpUrl+"MapResourceServlet");//urlRequest.method=URLRequestMethod.POST;// return urlRequest;// }// public function saveMapResource():URLRequest// {// var urlRequest:URLRequest=new URLRequest(httpUrl+"MapResourceDataServlet");//urlRequest.method=URLRequestMethod.POST;// return urlRequest;// }public static function getServlet():Servlet{if(servlet==null){servlet=new Servlet();}return servlet;}}}[文件] flex-messaging-common.jar ~ 92KB 下载(53)[文件] flex-messaging-core.jar ~ 599KB 下载(49)[代码] [Java]代码view sourceprint?<?xml version="1.0" encoding="utf-8"?><mx:Applicationxmlns:mx="/2006/mxml"layout="absolute" minWidth="955" minHeight="600"> <mx:Script><![CDATA[import cn.tianqi.game.servlet.Servlet;import mx.collections.ArrayCollection;private var loader:URLLoader=null;private var v:URLVariables=null;private var urls:URLRequest=null;protected function mapResource_clickHandler(event:MouseEvent):void{loader=new URLLoader();loader.dataFormat = URLLoaderDataFormat.BINARY;loader.addEventListener(PLETE, loaderHandler);loader.addEventListener(SecurityErrorEvent.SECURITY_ERRO R, loaderHandler);loader.addEventListener(IOErrorEvent.IO_ERROR, loaderHandler);// v=new URLVariables();// v.type=2;//urls=Servlet.getServlet().mapResource();urls=Servlet.getServlet().allServlet();//urls.contentType = 'applicatoin/octet-stream';var obj:Object=new Object();obj.n="南泥湾";obj.w=201;obj.h=150;obj.ms="101010100000001111000011111000000000";var dt:ByteArray=new ByteArray();dt.writeByte(100);obj.dt=dt;var obj1:Object=new Object();obj1.method="mapDataSave";obj1.data=obj;var byteArr:ByteArray=new ByteArray();byteArr.writeObject(obj1);urls.data=byteArr;// urls.data=v;loader.load(urls);}protected function loaderHandler(event:Event):void{trace(event.type);switch(event.type){case PLETE:var byte:ByteArray = event.target.data as ByteArray;byte.uncompress();var obj:Object = byte.readObject();var arr:ArrayCollection=obj as ArrayCollection;break;}}]]></mx:Script><mx:Button id="mapResource" label="点击我" click="mapResource_clickHandler(event)"/></mx:Application>。

flex DB

flex DB

一、首先我们先在phpMyAdmin里建立一个数据库"flexphp",然后建立一个表格"flexs",表格结构为"id,name,phone,adress"这四个,设置id为主KEY。

在这方面,我就不多说了,估计大家都知道。

二、重头戏来了,建立一个Flex Project,在向导里,第一步,我们命名这个项目叫"TestPhp"。

注意,注意,在第二步的时候,要像我截图那么设置。

在Server type里选择PHP。

三、选择完PHP,下面就出现选项,这里很重要。

一定要注意的,我的PHP是是WAMP5构建的,放在D盘下,那么,"Web root"就是"D:\wamp\www".接着在下面填上:http://localhost/,而下面的那个"Validata Configuration"可以确认是否生效,然后点击"Next"。

四、在这里,你可以按照默认设置直接NEXT,但是如果你要重新在WWW设置文件名,或者已经建立了文件,可以把Use default location勾选去掉,然后选择你要的文件。

五、这里要注意的是,那个Output folder URL,你可以自己设置,我这里就默认了。

千万不要设置错误。

还有要说的是,在这一步,你可以用RSL来减少等下要生成SWF的体积,具体怎么做,我在上一篇文章里说到了,你可以去这里查看。

开始的基本都设置完了,点Finish.六、在生成完文件后,别停下,选择DATA - Create Database Accessor ,进入设置数据库向导。

然后会出现一个红叉,没关系,点右边的"new",在向导的第二页,根据你的需要来选择。

我这里是最后一个MYSQL向导,然后NEXT。

七、在Name里随便写个名字,我这里是"phptestdata".其他的不用填写。

Flex考试题

Flex考试题

Flex综合测试题1)下面关于RIA的概念说法错误的是(C )A)RIA将桌面应用程序的强交互性与传统Web应用灵活的结合起来B)RIA的富客户端采用异步的方式同服务器端通讯C)RIA在通讯中会传输所有的数据,增加了数据的信息量D)RIA可以整合声音,视频等桌面元素2)一下关于Flex程序说法不正确的是( D )A)Flex程序由*.MXML、*.as、*.css文件组成B)MXML语言专用于Flex程序中,是用于描述界面表现的一种XML标记语言C)ActionScript是针对Adobe Flash Player运行环境的编程语言D)MXML提供了一系列标签供用户使用,MXML不区分大小写3)一下关于Applicaton布局的说话,错误的是( D )A)Application默认的布局是BasicLayoutB)HorizonatalLayout表示水平布局方式C)VertiacalLayout表示竖直布局方式D)TileLayout表示主题布局方式4)关于一下代码的说法,不正确的是(A )<mx:StringValidator source="{textPwd}" Property="text" Trigger="{submit}"triggerEvent="click"/>A)当用户单击提交按钮时,会触发StringValidator验证对象B)当用户单击id为sumit的按钮时,会触发StringValidator验证对象C)StringValidator验证对象验证的目标是id为txtPwd的输入组件D)StringValidator验证对象验证的是txtPwd的text属性5)下面不是为了实现RIA的技术是(A )A)XMTLB)AJaxC)EXTD)Flex6)下面关于Flex自定义组件,说法正确的是(AC)A)自定义组件提高了代码的重用性,降低了维护的难度B)一般讲程序中不常用的功能定义成自定义组件C)一般将程序中通用的功能定义成自定义组件D)一般讲程序中独立的功能定义成自定义组件7)下面关于Flex编译过程说法正确的是( C )A)将ActionScript语言编译成MXML语言B)将ActionScript编译成CSS语言C)将MXML语言编译成ActionScript语言D)将MXML语言编译成css语言8)下面是用于验证日期的是( D )A)<mx:StringValidatorB)<mx:EmailValidatorC)<mx:PhoneNumberValidatorD)<mx:DateValidator9)下面产生单选按钮的是( C )A)labelB)groupC)groupNameD)Groups10)下面关于TextInput的属性说法不正确的是( B )A)text表示得到用户输入的信息B)password表示以密码的形式显示信息C)restrict用于限定用户的输入D)Editable用于限定文本框是否可以输入11)下面对restrict的赋值能够限定文本框中仅能输入数字的是( B )A)$0-9B)0-9C)$0-9^D)0912)下面消息提示框Alert的说法正确的是( B )A)只能生成类似JavaScript的alert提示框B)能够生成类似JavaScript的conform效果C)只能指定消息的内容,不能为弹出框指定标题D)以上说话都不对13)AdvancedDataGrid组件用于绑定数据的属性是(C )A)designViewDataTypeB)columnsC)dataProviderD)data14)下面关于AdvancedDataGrid的显示形式说法正确的是( C )A)只能平面的形式B)只能是树形结构C)可以是平面结构,也可以是树形结构D)以上说法都不对15)关于AdvancedDataGrid绑定数据类型说法正确的是(D )A)只能是ArrayCollection数据类型B)只能是XML数据类型C)只能是XMLList类型D)可以是ActionScript定义的对象数组16)下面关于AdvancedDataGrid说法正确的是( B )A)AdvancedDataGrid不能对数据进行分组B)AdvancedDataGrid能够轻松实现显示摘要的效果C)不能对AdvancedDataGrid中的数据进行操作D)AdvancedDataGrid不能实现排序的功能17)下面关于Flex实现菜单导航效果的说法正确的是(C )A)利用tree组件完成菜单导航的效果B)利用AdvancedDataGrid实现菜单导航的效果C)利用MenuBar实现菜单导航的效果D)以上说法都不对18)下面关于Flex的动画效果说法正确的是(A )A)Flex可以利用定义好的组件,轻松的实现动画效果B)Flex不支持3D的动画效果C)Flex只能利用MXML组件实现动画效果D)Flex动画效果做起来很难,一般都不用19)下面关于淡入淡出效果说法正确的是( A )A)alphaFrom的值大的时候从不透明向透明转变B)alphaFrom的值大的时候从透明向不透明转变C)alphaFrom的值可以比1大D)alphaFrom不能比alphaTo 的值大20)关于Move3D动画效果说法正确的是( C )A)实现旋转功能B)实现淡入淡出功能C)实现移动功能D)实现变大变小功能21)关于Rotatee3D动画效果说法正确的是(A )A)实现旋转功能B)实现淡入淡出功能C)实现移动功能D)实现变大变小功能22)下面关于Flex移动动画说法正确的是(D )A)Flex的移动不能重复B)Flex的移动只能向一个方向移动,不能同时向多个方向移动C)Flex向Z轴方向的移动的值不能小于0,小于0会报错D)Flex向Z轴方向的移动的值能小于0,当小于0的时候表示向外移动23)关于Flex动画效果的持续时间说法正确的是(B)A)Flex动画的时间不能设定,都是1秒B)时间可以设定,用duration属性来设置持续时间C)Duration默认的时间用毫秒计算,如果需要持续3秒钟,其值应该是30000 D)Duration默认的时间用秒计算,如果需要持续3秒钟,其值应该是3 24)下面说法正确的是(B )A)Flex的动画效果一次只能使用一个,不能联合使用B)Flex的动画可以联合使用,但是有先后顺序C)Flex的动画可以联合使用,没有先后顺序D)以上说法都不对25)对于Tree组件的labelField属性赋值,正确的是( C )A)#labelB)$labelC)@labelD)%label26)在使用<s:Fade组件淡出淡入效果时候,alphaFrom属性的值正确的是(C )A)2 B)10 C)0.5 D)-127)在AS3.0中,用于创建Array数组正确的代码是( D )A)var Array temp = new Array();B)var temp:Array = new Array["a","b","c"];C)var temp:Array = ("a","b","c");D)var temp:Array = new Array("a","b","c");28)关于ArrayCollection过滤功能说法正确的是(AD )A)使用filterFunction属性指定过滤的函数名B)使用filter属性指定过滤的函数名C)ArrayCollection过滤函数类型必须是Boolean类型D)必须调用refresh方法使过滤生效29)关于Flex中视图状态,说法正确的是(BC )(选择两项)A)应用程序默认的视图状态为default视图状态B)应用程序默认的视图状态为在<s:states >中定义的第一个状态C)includeIn表示向视图中添加组件D)excludeFrom表示向视图中添加组件30)能够正确从目标对象的dragDrop事件中获取拖放数据的是(B )A)var dgRow:Object=event.dragSource.dataForFormat("item")[0];B)var dgRow:Object=event.dragSource.dataForFormat("items")[0];C)var dgRow:Object=event.dragSource.dataForFormat("items");D)var dgRow:Object=event.dragSource.dataForFormat("item");31)关于ActionScript说法正确的是( C )A)ActionScript是一个纯面向对象的编程语言B)ActionScript是一个纯面向过程的语言C)ActionScript是一个综合了面向过程和面向对象的编程语言D)以上说法都不对32)下面关于ActionScript面向对象的说法正确的是( C )A)ActionScript不支持重写B)ActionScript不支持继承C)ActionScript不支持重载D)ActionScript不支持封装33)Math.round()函数说法正确的是(BC )(选择两项)A)本函数支持保留小数B)本函数不支持保留小数,只能保留整数C)本函数是利用四舍五入的方式进行操作D)本函数是利用只舍不余的方式进行操作34)在ActionScript中如果要将数字进行四舍五入,并且保留小数,使用的方法是(D )A)Math.round()B)Math.floor();C)Math.ceil();D)Number.toFixed()35)ActionScript中循环说法正确的是(D)A)for循环,for in循环,for each循环是一样B)for循环不一样,for in和for each循环是一样C)for循环和for in循环是一样,for each不一样D)for循环,for in循环,for each循环都各有特点,不一样36)下面创建数组,错误的是( C )A)var bookArr:Array=new Array();B)var bookArr:Array=new Array("java","jsp","flex");C)var bookArr:Array=();D)var bookArr:Array=[“java”,“jsp”,“flex”];37)下面关于数据绑定的说法错误的是( C )A)使用数据绑定时,Flex会自动将一个对象的数据复制,提供给另一个对象使用,提供数据的一方称为数据源对象,使用数据的一方称为目标对象B)当数据源对象的数据发生改变化时,目标对象的数据会自动更新,而不需要再编写代码去强制更新C)当数据源对象的数据发生改变化时,目标对象的数据不会自动更新,需要再编写代码去强制更新D)绑定的实现是借助于事件机制来完成的38)下面关于AdvancedDataGrid拖放功能说法正确的是( A )A)dragEnabled="true"表示能够拖动B)dragEnabled="false"表示能够拖动C)dropEnabled="true" 表示能够拖动D)dropEnabled="false" 表示能够拖动39)下面关于Flex页面跳转的方式说法正确的是(A )A)可以使用ActionScrip调用JavaScript来实现跳转B)ActionScript是同JavaScript不同的编程语言,ActionScript不能使用JavaScript来实现页面的跳转C)JavaScript调用ActionScript来实现页面的跳转D)以上说法都不对40)下面关于HttpService组件的说法正确的是(B )A)是直接调用Java类的进行通信的方式B)是来通过Http请求的方式来同后台进行通信C)是同WebService进行通信的一种方式D)是调用Flex其他组件的一种方式41) 下面关于HttpService来进行通信的说法正确的是(B )A)服务器端可以直接以Java对象来响应客户端的请求B)服务器只能通过xml,Json对象等的形式来响应客户的请求C)服务器必须通过WebService的方式来响应请求D)以上的方式都行41)下面关于WebService组件说法正确的是( C )A)是直接调用Java类的进行通信的方式B)是来通过Http请求的方式来同后台进行通信C)是同WebService进行通信的一种方式D)是调用Flex其它组件的一种方式42)下面关于Remoting组件说法正确的是( A )A)是直接调用Java类的进行通信的方式B)是来通过Http请求的方式来同后台进行通信C)是同WebService进行通信的一种方式D)是调用Flex其他组件的一种方式44)下面关于Flex直接调用Java类的说法正确的是(C )A)Flex只能调用普通的Java类,不能调用被Spring管理的类B)Flex可以直接调用Java类,不需要借助任何的其他的插件C)Flex调用Java类的时候需要增加一个插件D)以上的说法都对45)下面关于Flex调用Java类的说法正确的是( D )A)需要将要被Flex调用的Java类注册到flex-config.xml文件中B)需要将要被Flex调用的Java类注册到service-config.xml文件中C)需要将要被Flex调用的Java类注册到application-config.xml文件中D)需要将要被Flex调用的Java类注册到remoting-config.xml文件中46)下面关于Flex直接调用Java类的说法正确的是(C)A)只能传递文本数据,不能传递对象B)只能传递对象,不能传递文本数据C)能够传递对象,但是对象需要系列化D)能够传递对象,|对象不需要系列化47)下面关于HttpService说法正确的是(D )A)HttpService只能访问JSP不能访问Servlet,B)HttpService只能访问Servlet,不能访问JSPC)HttpService即不能访问JSP,又不能访问ServletD)HttpService即能访问JSP,又能访问Servlet48)下面关于Flex同后台通信说法正确的是(AD)(选择两项)A)必须通过回调函数得到服务器端的响应B)不需要通过回调函数,能够直接得到服务器端的响应C)只能捕获正确的响应,不能捕获错误的响应D)即能捕获正确的响应,又能捕获错误的响应49)关于Flex图表说法正确的是(C )A)Flex只能绘制静态的图表,没有实用价值B)Flex只能绘制简单的图表,没有实用价值C)利用Flex的图表功能能够轻松的绘制出各种动态的图表,功能强大D)Flex的图表组件功能强大,不需要借助任何组件,可以直接同后台进行通信50)下面关于<mx:LineChart>说法正确的是(B )A)是绘制饼图的组件B)是绘制线性图表的组件C)是绘制柱状图的组件D)是绘制表格的组件。

FLEX学习笔记(崔宏峰)0309

FLEX学习笔记(崔宏峰)0309

FLEX学习笔记贵在坚持崔二宏零峰一一年二月十七一、配flex环境需要软件:1.j dk2.t omcat3.m yeclipse4.f lex builder 插件5.b lazeds.war其它的安装比较简单。

只是装flex builder时注意。

有一步要选myeclipse的安装路径才行。

然后把D:\Program Files\adobe\Adobe Flash Builder 4 Plug-in\eclipse下的features和plugins文件夹放在myeclipse的D:\Program Files\Genuitec\Common 下(myeclipse8以后就是这种路径。

7好像是单独有一个eclipse文件夹),然后还有一个AMT文件夹放到D:\Program Files\Genuitec\MyEclipse-8.6\AMT文件夹(这个不知道是为啥)(注:也有人不拷贝这些。

只是像上边那样直接安装。

行不行有待考证)二、建立采用flex的web工程因为flex只是做为表示层展示,flex只接收java返回数据,那怎么和java服务端通信呢?这时我们需要用到adobe公司开发的一个开源项目Blazeds。

Blazeds是一个基于服务器的Java 远程控制(remoting) 和Web 消息传递(messaging) 技术,以LGPL(Lesser GNU Public License)公共许可证书发布。

它能够使得后端的Java 应用程序和运行在浏览器上的Adobe Flex 应用程序相互通信。

在Java应用服务器上,它以servlet的形式存在,因此可以在任何标准Java 网络应用中运用它。

下载好核心包解压出来就发现一个文件名是Blazeds.war,我们只需要把Blazeds.war改成Blazeds.rar然后解压就会出现:1.打开Myeclise8.0新建一个javaweb工程,选择javaEE 5.0如图2.把blazeds解压后的2个文件夹覆盖到WebRoot下面,展开发现在WEB-INF 目录下面多了flex文件夹,这个很重要主要是通信的4个配置文件。

Flex基础

Flex基础
ห้องสมุดไป่ตู้
Flex安装配置
解决创建的错误如下图
找到Problems看到有一个错误后肉我们右键选重新创 建HTML模板。这里错误已经解决,但是新的问题又 来了,src是java的源文件夹存java源代码的地方,但 是现在被 flex占用了
Flex安装配置
更改flex的项目源文件为flex_src,右键项目属性找到 flex构建路径的主源文件夹把src改为flex_src如下图
使用ActionScript
While和do while
while循环在循环开始前检查条件;如果循环开始条件 不成立,则不会执行 do while 在循环结束后检查条件,这就适合无论测试条 件是否 成立,都至少将部分代码运行一次。
使用ActionScript
条件语句(if和switch)
Flex安装配置
然后把src文件夹 里面的flexweb.mxml移动到flex_src 文件夹里面。最终目录如下图
(二)实现Flex与JAVA通信
实现Flex与JAVA通信
在src目录创建Java文件MyTest如下图
实现Flex与JAVA通信 配置WebRoot/WEB-INF/flex/remoting-config.xml 如下图
Flex的ActionScript支持两种主流注释形式:行内注释和多行注释 行内注释
行内注释以双斜杠开头,从双斜杠到当前行末尾之间的文本是一条 注释。换行意味着注释结束。
多行注释
如果想添加更多的注释用多行注释,多行注释的开始位置以斜杠加 星号(/*)标示。结束位置以星号加斜杠(*/)
很多时候不方便在MXML创建组件中 的定义事件,如组件是根据动 态 数据创建的,这些事件就需要使用Actionscript代码来动态的定义 事件。

基于面向服务体系架构(SOA)和面向资源体系架构(ROA)的业务组件模型

基于面向服务体系架构(SOA)和面向资源体系架构(ROA)的业务组件模型

基于面向服务体系架构(SOA)和面向资源体系架构(ROA)的业务组件模型多终端多技术平台可复用的组件模型引言在《面向服务体系架构(SOA)和业务组件(BC)的思考》(以下简称《SOA 和BC 》)一文中介绍了基于面向服务体系架构(SOA)的组件模型,本文按照“分离”的原则,通过比较当前多种流行的客户端和服务器端的通讯机制,进一步把业务组件进行分离,采用面向资源体系架构(ROA)把业务组件界面层和业务逻辑层分离开,构建一个多终端多技术平台可复用的组件模型多层架构中的通讯方式软件体系架构是沿着单机到CS 架构,再到BS 的三层架构甚至多层架构逐步发展过来的,关于多层架构,本文不再详细介绍,可以参考相关的资料,下面首先来分析一下当前比较流行的客户端技术以及客户端和服务器之间的通讯方式。

基于MVC 的J2EE 多层模型在一个标准的基于MVC 的J2EE 的模型架构的代码中,从对象的类别来看,一般包含BO、DAO、POJO 等Java 类,另外还包含JSP、Servlet 等,如下图所示:图1. 基于MVC 的J2EE 多层模型POJO:简单Java 对象(Plain Ordinary Java Object,POJO),一个中间对象,在不同阶段可以转化为PO、DTO、VO,POJO 持久化以后就是PO,在应用中的不同层次传递为DTO,直接用来对应表示层就是VO。

PO:持久对象(Persistant Object,PO),也称为Data 对象,对应数据库中的Entity,可以简单认为一个PO 对应数据库中的一条记录。

PO 中不包含任何对数据库的操作。

VO :表现层对象(View Object,VO)主要对应界面显示的数据对象。

对于一个WEB 页面,或者SWT、SWING 界面,用一个VO 对象对应整个界面的值。

根据业务的需要可以和表对应,也可以不对应。

DTO :数据传输对象(Data Transfer Object,DTO)主要用于远程调用等需要大量传输对象的地方。

flex 调用 servlet

flex 调用 servlet
txt1.text = event.result as String;
}
private function faultHandler(event:FaultEvent):void{
var fault:Fault = event.fault;
var s : String = (fault.faultDetail != null)? fault.faultDetail : fault.faultString;
<mx:TextArea x="27" y="58" width="450" height="143" id="txt1"/>
</mx:Application>
servlet代码:
package com;
import java.io.IOException;
import java.io.PrintWriter;
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.Fault;
private function call():void{
public class JspServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,HttpServleቤተ መጻሕፍቲ ባይዱResponse response) throws ServletException,IOException{

Flex培训

Flex培训

24
Content 内容
Flex简介 Flex示例 Flex与J2EE应用结合 常见问题的解决方案 Flex开发框架
Inspur group 2012-2-28
25
Flex与J2EE的结合:新建项目时 Flex与J2EE的结合: 的结合
选择J2EE型的应用服务类型
26
Flex与J2EE的结合:新建项目时 Flex与J2EE的结合: 的结合
编辑应用服务地址,引用url,上下文
编辑完了要点击检验正确性
27
Flex嵌入html,jsp Flex嵌入html, 嵌入html
参照你应用下的bin目录下的html文件
28
Flex嵌入html,jsp Flex嵌入html, 嵌入html
29
在Flex里访问传入的参数 Flex里访问传入的参数
11
Flex的优势五:自动解析xml文件 Flex的优势五:自动解析xml文件 的优势五 xml
Flex中的Actionscrip包含了针对XML的Ecmascript或者 叫做E4X。它通过把XML看作一个原始变量使得操作一个 XML对象变得简单。 Xml对象及其子元素还可以直接作为Tree,DataGrid对象 的数据集,直接以图形化的方式进行展现。
<?xml version="1.0" encoding="utf8"?> <mx:Application xmlns:mx="/20 06/mxml" layout="absolute"> <mx:Button id="btn" lab el=" 确定"/> </mx:Application>

java用XFire调用webservice例子

java用XFire调用webservice例子

java用XFire开发调用webService例子XFire 概述XFire 是codeHaus 组织提供的一个开源框架,它构建了POJO 和SOA 之间的桥梁,主要特性就是支持将POJO 通过非常简单的方式发布成Web 服务,这种处理方式不仅充分发挥了POJO 的作用,简化了Java 应用转化为Web 服务的步骤和过程,也直接降低了SOA 的实现难度,为企业转向SOA 架构提供了一种简单可行的方式。

XFire 目前最新的版本是1.2.2,目前支持的特性主要包括:支持将Web 服务绑定到POJO、XMLBeans、JAXB1.1、JAXB2.0 和Castor;支持基于HTTP、JMS、XMPP 等多种协议访问Web 服务;支持多种Web 服务业界重要标准如SOAP、WSDL、Web 服务寻址(WS-Addressing)、Web 服务安全(WS-Security)等;支持JSR181,可以通过JDK5 配置Web 服务;高性能的SOAP 实现;服务器端、客户端代码辅助生成;对Spring、Pico、Plexus 等项目的支持等。

XFire 安装包XFire 框架目前的最新版本是1.2.6,可以访问 下载XFire 框架的安装包,下载时请选择“全部二进制发布包(Binary Distribution in zip package)”,而不仅仅是“XFire jar 文件(Jar of all XFire modules)”。

下载完成后,我们可以将下载的.zip 文件解压缩到任意的文件夹中(后面的章节中使用% XFIRE_HOME % 表示XFire 框架的安装目录),解压缩后形成的文件目录结构如下:api(目录)api 目录中是XFire 框架中所有类(class)对应的API 文档,为开发者使用XFire 完成应用开发提供帮助。

examples(目录)examples 目录中包含了所有随XFire 二进制包发布的实例,包括这些实例的源代码和相关Web 应用配置内容。

flex语言

flex语言

1.了解Flex在如今这个以用户为中心的时代,用户体验越来越重要,用户不仅要求应用要像C/S模式的应用那样具有良好的交互性,而且要求应用要像B/S模式的应用那样具有部署灵活和跨平台的优势。

RIA技术便是在这种需求下应运而生的,它同时具备B/S模式和C/S模式应用的双重优势,很好地满足了现代用户的需求Flex, Silverlight, JavaFx ,Html5四种语言:1. 必须支持Java作为后台语言,且能够与JSF/JSP开发的系统集成。

2. 必须有成功案例可以借鉴,成功案例多则优先考虑。

3. 有成熟的IDE,支持拖拽编程和跟踪调试。

如果能基于我们所熟悉的Eclipse集成开发环境,则会优先考虑。

能够满足这些要求的就只有FlexFlex是排版打印软件和图形渲染软件巨头Adobe公司在其著名的Flash平台(Flash Player)上,用ActionScript语言开发的一套RIA软件开发套件(SDK)及其集成开发环境。

开发人员可以将RIA程序编译成为Flash文件,为Flash Player所接受,也就是说,Flex技术所开发出来的程序对于大部分浏览者而言并不需要安装额外的客户端支持,这是一个得天独厚的优势。

2.语言及数据Flex程序以下三个文件组成:以css为后缀的样式表文件以mxml为后缀的程序文件以as为后缀的ActionScript文件2.1MxmlMXML语言是专门用于Flex程序中,描述界面表现的一种XML标记语言。

我们可以用它来管理程序的整体布局,控制组件的样式和外观,也可以构建非可视化的对象,比如XML数据,组件的数据源等。

MXML标签与ActionScript类或者类中的属性是相对应的。

当你编译你的Flex应用程序的时候,Flex解析你的MXML标签并且生成相应的ActionScript类。

然后这些ActionScript类会被编译成SWF字节码存储到一个SWF文件中。

flex和java 集成,主要讲述flex获取java的数据服务

flex和java 集成,主要讲述flex获取java的数据服务

So far, you know how to combine Flex and Java using HTTP and web services. The lastchapter surveyed a bunch of alternative mechanisms to achieve this. Most of thesemechani sms i nvolve loosely coupled text-based data i nterchange. Most of theminteract by pulling data. Only one of them, Hessian, transmits binary data. Only one,Hessi an agai n (wi th addi ti onal i nfrastructure powered by the new Java IO), allowsdata push.Now, we delve into more tightly coupled scenarios and efficient binary data transmis-si on usi ng AMF (Acti on Message Format). The AMF speci fi cati on can be accessedonline at . This chapter looks at both pull- and push-based interactions—using data services and media servers. Adobe offers two alterna-tives for data services—the commercial LifeCycle Data Services (LCDS) and the opensource BlazeDS—and it offers a suite of products for media servers: Flash Media Server(FMS) products. There are a few open source alternatives to these as well.In this chapter, I will analyze these products in the context of their applicability torich, engaging enterprise-grade applications. Functionally they can be divided intothe following three topics:Remoting and RPCMessaging and data push Media streaming 257INTEGRATING VIA DATA AND MEDIA SERVICESBy Shashank Tiwari Chapter 7At this point of the book, remoting and RPC should be familiar territory, so let’s start there.Remoting and RPCFlex applications can access the Java server side using data services. They can access Java objects and nvoke remote methods on them. The Flex framework ncludes a cl ent-s de component called RemoteObject . This object acts as a proxy for a data service destination on the server. When config-ured properly, this object handle can be used to invoke RPCs. Before we get into the nitty-gritty of this object and destination configuration, let’s step back and look at the data services architecture.Data services architecture Figure 7-1 is a pictorial summary of the data services architecture. The view is biased to highlight thefunctional elements. It includes technical aspects but skips the internal details in many places. As you look deeper into the nuts and bolts in this chapter, many of these details will emerge.As Figure 7-1 depicts, data services includes the following:Gateway to intercept server-bound callsParser to make sense of AMF messagesSerializer and deserializer to transform objects between ActionScript 3.0 (AS3) and JavaManager to coordinate with and delegate responsibility to server-side objectsMessaging service provider to send and receive messagesBy data services, I mean a class of products that enable remoting and messaging over AMF and proto-cols like Real Time Messaging Protocol (RTMP). RTMP is a proprietary protocol developed by Adobe Systems for streaming audio, video, and data over the Internet. More information on RTMP can be found on W i k i ped i a at /wiki/Real_Time_Messaging_Protocol and at /documentation/rtmp .As mentioned, there are two data services implementations from Adobe and a few open source alter-natives. Following are the most popular ones:LifeCycle Data Services (Adobe): /products/livecycle/dataservices/BlazeDS (open source from Adobe): /wiki/display/blazeds/Granite Data Services (GDS):/WebORB for Java : /weborb/java/OpenAMF :/projects/openamf/OpenAMF is not a very active project at the time of writing. The last release dates back to 2006. This project’s mission was to port AMFPHP to Java. AMF was a closed specification back then, and AMFPHP was a reverse-engineered open source option for PHP servers. OpenAMF is closer to Flash remoting than data services.This chapter sticks mostly to LCDS and BlazeDS, but the same concepts apply to the alternatives. LCDS and BlazeDS are quite similar in form and structure and share the same codebase. BlazeDS can be thought of as a marginally scaled-down version of LCDS.258CHAPTER 7Figure 7-1. Data services architecture: an overviewData services uses AMF3 (Action Message Format version 3) to transmit binary data between Flex and Java. The genesis of this product lies in the Flash remoting server, which used to support AMF0 as the binary protocol. Flash remoting still exists, in many forms, but data services replaces it as a better alternative.Whichever data service we choose, it is a web application from a Java server perspective. Let’s dig a bit deeper to see what this means. (Of course, we are talking only about data services for Java. There are remoting servers for other technologies,but that is beyond the scope of this book.)259INTEGRATING VIA DATA AND MEDIA SERVICESIt’s a web applicationWeb applications are applications built on the technology that powers the Web. The HTTP protocol and the associated programming paradigm are a prominent part of this technology set. In Java, the raw low-level HTTP and related infrastructure is abstracted out as a higher-level API and managed components. At the heart of this abstraction is the Servlet specification, which wraps HTTP methods and HTTP protocol handling in objects. Web applications written in Java are packaged with all assets,associated libraries, class files, and any other resources into a special archive file format: a web appli-cation archive (WAR). These WAR files are deployed on a servlet container or an application server (which contains a servlet container).Most data servi ces, especi ally LCDS and BlazeDS, are web appli cati ons and exi st as WAR fi les. The remoting gateway is a servlet, and data service elements are web components. A little later, in the sec-tion “Downloading and deploying the web application,” you will see how deploying LCDS or BlazeDS is identical to deploying any other web application distributed in a WAR file format.In both BlazeDS and LCDS, the primary communication responsibilities are handled by a message bro-ker, which is created on startup by a servlet called the MessageBrokerServlet . The application server’s standard class loader loads it like any other servlet. This message broker is extremely flexible, and all types of available services and endpoints can be configured for it fairly easily. All such configurations reside in an XML configuration file, which I talk about later in the section “Configuring data services.”Protocols, channels, destinations, and endpointsOne of the primary advantages of data services is their use of AMF to transmit data between Flex and Java. AMF is a binary protocol, and the Flash Player natively supports it. Therefore, transmission using AMF is fast and efficient. AMF is a high-level (application layer) protocol that uses HTTP for commu-nication. Almost all data services dialog happens over HTTP or its secure alternative, HTTPS. AMF spec-i f i cat i on i s now ava i lable under the open source l i cense and i s access ible for download at /pub/labs/amf/amf3_spec_121207.pdf . When remot ng, AMF s marshaled and unmarshaled at both ends (Java and Flex) for the data interchange to work.The data services messaging module and media server use RTMP. LCDS and FMS support RTMP, but BlazeDS does not. BlazeDS uses HTTP tunneling and AMF long pooling to achieve a push-based model.Red5 (/red5), an open source alternative to Flash Media Server, partially reverse-engineers RTMP and provides streaming capabilities over this derived protocol.Apart from AMF over HTTP and RTMP, the Flash Player also supports Transmission Control Protocol (TCP) over Sockets. TCP is a protocol from the Internet protocol suite that facilitates reliable ordered delivery of byte streams. Secure versions of the protocol, such as AMF and HTTP over Secure Sockets Layer (SSL) and RTMP over Transport Layer Security (TLS), can be used as well. Both SSL and TLS are cryptographic protocols that facilitate secure communication over the Internet. TLS is a newer gener-ation protocol compared to SSL. Although similar, SSL and TLS are not interchangeable. TLS 1.0 is a standard that emerged after SSL 3.0. These protocols nvolve endpo nt authent cat on, message ntegri ty, and key-based encrypti on. Both protocols support a bunch of cryptographi c algori thms including RSA. RSA is a popular cryptographic algorithm for public key cryptography, which involves two different keys, one to encrypt a message and another to decrypt it.260CHAPTER 7INTEGRATING VIA DATA AND MEDIA SERVICES The Flash Player does not support the entire repertoire of protocols and even misses the ubiquitousUser Datagram Protocol (UDP), whi ch i s very useful for multi casti ng.Multicasting i s a method ofi nformati on deli very to multi ple desti nati ons si multaneously whereby messages are deli vered overeach link of the network only once. Copies of the message are created only if the links to the destina-tions bifurcate.You will not be able to take advantage of protocols like UDP with data services.Protocols help make effecti ve and effi ci ent communi cati on possi ble, but hi gher-level abstracti onsincrease the usability of these protocols. These higher-level abstractions help you focus on businesslogi c and reduce the burden of deali ng wi th low-level communi cati on handli ng. One such usefulhigher-level construct in Flex is called destination.Destinations are one of the key abstractions available in the Flex framework and data services. Server-side entities are mapped to logical names and configured to be invoked using these logical names.These confi gured server-si de elements, or desti nati ons, have a handle (logi cal name) and exposeserver-side functionality to remote clients. Many Flex client components, especially those that facili-tate remoting—for example RemoteObject—map to a destination. The section “Configuring data serv-ices,” which comes a little later, illustrates the configuration files. In that section, you will learn how todefine, configure, and use a destination. Then, in the section “Extending data services for advancedremoti ng use cases,” you wi ll see how to use custom extensi ons as desti nati ons. In data servi ces,almost all server-side elements that facilitate remoting and messaging are configured as destinations.HTTPService and WebService, when routed through a data service proxy, also map to a destination.When you i nteract wi th a server-si de servi ce vi a a desti nati on, you use a messagi ng channel to communicate back and forth.A messaging channel is a bundle that defines a protocol and an end-point set. An endpoint set means a URI, a listening port number, and an endpoint type definition. Forexample, an AMF channel could be established with the help of the AMF channel implementationclass (mx.messaging.channels.AMFChannel) and an endpoint definition, which could be a combina-tion of an endpoint type (flex.messaging.endpoints.AmfEndpoint) and its availability via a URI (say/sampleapp/messagebroker/amf) over a certain listening port (which by default for AMF is 8100).Sometimes, services need special adapters to communicate with server-side elements. These adaptersmay translate the message and act as the classical conduit that helps different programming interfacescommunicate and interact with each other. (An adapter by definition is something that modifies anAPI to make i t adapt to the requi red i ntegrati on scenari o.) Data servi ces defi ne a set of bui lt-i nadapters and provide an API to create your own.That is enough theory; time now to roll our sleeves up and see data services in action. We first installdata services and then quickly create a small example application to see how it works.Installing a data serviceThe last section claimed data services to be a Java web application. You will see that claim reinforcedby deploying a data service like any other Java web application in a Java application server (with aservlet container). Once we have deployed it successfully, we will go ahead and configure it so that weare ready to build an example application.261Downloading and deploying the web application For the purposes of illustration, we will pick BlazeDS as the data service and choose JBoss Application Server (AS) as the Java application server. If the data service is LCDS and the application server is any other, such as Apache Tomcat, BEA WebLogic, IBM WebSphere, Apache Geronimo, Caucho Resin, or GlassFish, the situation is not very different. Each of these application servers has its own directory struc-ture and styles of deployment. Deploying BlazeDS or LCDS involves the same level of complexity as deploying any other Java web application packaged as a WAR. Adobe Labs has published some notes on the specific installation instructions for a few of the popular application servers. These notes are online at /wiki/index.php/BlazeDS:Release_Notes#Installing_BlazeDS .The first step is to get all the required software and to install it.Getting the software and installing it BlazeDS is available under the open source GNU LGPL license.Go to /wiki/display/blazeds/BlazeDS and download the latest stable release build. You will have a choice to download the binary or the source versions. The binary version is what you should choose unless you intend to make modifications to the code. The distribution is available as a ZIP file. When you unzip the archive file, you will find a file called blazeds.war . This is the WAR file that has everything in it needed to use BlazeDS. In addition, you may find the following files:blazeds-samples.war : A set of sample applications blazeds-console.war : Monitoring application for BlazeDS deployments If this is the first time you are deploying BlazeDS, it’s recommended you deploy blazeds-samples.war and verify that the sample applications run without a problem.The other piece of the puzzle is the Java application server. I will assume that you have downloaded and installed one for your use. In this example, we download the latest stable release of JBoss AS from the communi ty download page accessi ble at /projects/download/. At the time of writing, version 4.2.2.GA is the latest stable release. This may differ depending on when you download it. The JBoss AS download is an archive file that is ready to use as soon as it’s expanded in the file system. (It may at most require a few environment variable settings.) On the PC, we just unzip it within a directory on the main partition.The JBoss AS dshown in Figure 7-2.BlazeDS runs w i th any Java appl i cat i support these JDK versions.Deploying the WAR file application in JBoss versing down the server ➤default ➤folders and copy ng the WAR f the bin appli cati on. In our case, JBoss i 262CHAPTER 7INTEGRATING VIA DATA AND MEDIA SERVICES port 8080 for HTTP requests, and so the URL for samples looks like this: http://localhost:8080/ blazeds-samples/. If you are able to access the samples application, you are ready to move to thenext step of configuring data service.With LCDS, the deployment is no different. The WAR file in LCDS has a different name—flex.war as opposed to blazeds.war—and it has a few extra features compared to BlazeDS, but from a deploy-ment standpoint things don’t change.GDS, the open source alternative to LCDS, has a slightly different approach to software distribution. GDSis distributed as multiple bundles, each integrating with one Java server-side technology. Also, GDS is dis-tributed as source and not binary, which means you need to set up the development environment tobuild the software. If you are a Java developer who also writes Flex applications, you may already havethe development environment set up. The required pieces of software areEclipse 3.2+ (with JDK 5+)Flex 3 SDK (If you use Flex Builder, you already have it.)Flex 3 Ant tasks (/wiki/index.php/Flex_Ant_Tasks)Once the environment is set up, you could get hold of one of these bundles:graniteds-ejb3-1.0.0.zip: Hooks to EJBgraniteds-seam-1.0.0.zip: Integrates with Seam (stateful web beans)graniteds-spring-ejb3-1.0.0.zip: Provides Spring servicesgraniteds-guice-1.0.0.zip: Provides services for Google Guicegranite-pojo-1.0.0.zip: Interfaces with plain Javagranite-chat-1.0.0.zip: Includes Java New I/O (NIO) and Comet-based data pushThe choice of bundle depends on your requirements. Also, the bundle version numbers could vary depending on when you download the files. As of now, the release version is 1.0.0. Each of these bun-dles i s an Ecli pse project. Once you get the bundle you need, unzi p i t and i mport i t i nto Ecli pse. Subsequently, you build it using Ant tasks.Configuring data servicesIn BlazeDS and LCDS, there is more to configure than code. In both these cases, a message broker servlet is the central manager of all communication and service invocations. Configuring data servicesis equivalent to configuring this message broker. In the web.xml file where you set up this servlet, you define the configuration file it should read. The portion of web.xml where you define this is as follows: <servlet><servlet-name>MessageBrokerServlet</servlet-name><display-name>MessageBrokerServlet</display-name><servlet-class>flex.messaging.MessageBrokerServlet</servlet-class><init-param><param-name>services.configuration.file</param-name><param-value>/WEB-INF/flex/services-config.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet>263You may not i ce that the value for the services.configuration.file is /WEB-INF/flex/services-config.xml . This is the default configuration, and most often there is no need to change it.However, if you need the configuration file to be at a different location or have a different name, you know where to make the modifications so that the new values are picked up.All servi ce and endpoi nt confi gurati ons are speci fi ed i n thi s confi gurati on fi le, whi ch by default i s called services-config.xml . From a functi onal standpoi nt, a data servi ce tri es to accompli sh the following:Facilitate remote procedure calls to Java objects on the server and transmit data between AS3and Java classes.Provide proxy services, especially for HTTPService and WebService , where security restrictions (the lack of a cross-domain definition via crossdomain.xml ) disallow these services otherwise.Send/Receive messages between Flex and Java and between two different Flex clients.Manage data for the application. This topic is not discussed in this book at all. BlazeDS does not provide this off the shelf, but LCDS does.Therefore, Adobe partitions the configuration file into four different pieces, each corresponding to one of the functional responsibilities just listed. Each of these pieces resides in a separate file, and all are included in the original configuration file by reference. The default names for these four files, in the same order in which they correspond to the functional areas listed previously, are remoting-config.xml proxy-config.xml messaging-config.xml data-management-config.xml The portion of services-config.xml at /flex/WEB-INF from our BlazeDS installation, where three of these four files are included (BlazeDS does not have data management features), is as shown here:<?xml version="1.0" encoding="UTF-8"?><services-config><services><service-include file-path="remoting-config.xml" /><service-include file-path="proxy-config.xml" /><service-include file-path="messaging-config.xml" /></services>A few aspects like logging, security, and channel definitions are cross-cutting concerns and are used across services, so these are defined in services-config.xml itself. All other service configurations and definitions typically fall in one of the four files (or three if we are using BlazeDS) I spoke about.In this chapter, there is no intent to cover every single aspect of configuration. Only a few important ones are sampled and explained. For an exhaustive syntax-level account of each allowed configura-tion, it’s advisable to refer to the LiveDocs. For BlazeDS, you could refer specifically to a LiveDocs sec-t i on t i tled “About serv i ce conf i gurat i on f i les,” wh i ch can be found onl i ne at /blazeds/1/blazeds_devguide/help.html?content=services_config_2.html .Let’s survey a few configuration options to get a flavor of things.264CHAPTER 7INTEGRATING VIA DATA AND MEDIA SERVICES Common configuration Let’s start with logging. BlazeDS and LCDS use log4j for logging. Logging-related configurations reside in services-config.xml itself. The most important aspect of configura-tion is the logging level. The permissible values and their respective meanings are as follows: ALL: Logs every single message.DEBUG: Includes internal Flex activities. This is an appropriate level during development andtroubleshooting, and is an incremental expansion beyond INFO. Therefore, all errors, warningsand information messages are included.INFO: Logs additional information that may be pertinent to developers or administrators. Thislevel builds on top of the WARN level.WARN: Includes warnings as well as errors.ERROR: Logs only errors that cause service disruption.NONE: Logs nothing.If you are familiar with log4j logging levels, then you have seen this before.Next come channel definitions. In terms of importance, this rates above the logging-level definitions. Channels are the vital protocol and endpoint combination that make communication possible betweenthe Flex client and the server. In BlazeDS, the default AMF channel configurations look like this: <channels><channel-definition id="my-amf" class=➥"mx.messaging.channels.AMFChannel"><endpoint url="http://{}:{server.port}/➥{context.root}/messagebroker/amf"class="flex.messaging.endpoints.AMFEndpoint"/></channel-definition><channel-definition id="my-secure-amf"class="mx.messaging.channels.SecureAMFChannel"><endpoint url="https://{}:{server.port}/➥{context.root}/messagebroker/amfsecure"class="flex.messaging.endpoints.SecureAMFEndpoint"/><properties><add-no-cache-headers>false</add-no-cache-headers></properties></channel-definition><channel-definition id="my-polling-amf"class="mx.messaging.channels.AMFChannel"><endpoint url="http://{}:{server.port}/➥{context.root}/messagebroker/amfpolling"class="flex.messaging.endpoints.AMFEndpoint"/><properties><polling-enabled>true</polling-enabled><polling-interval-seconds>4</polling-interval-seconds></properties></channel-definition></channels>265Three di fferent AMF channels are defi ned usi ng the precedi ng confi gurati on. In each case, a fully qualified class name specifies the class that implements the channel. The channel is accessible via a configured endpoint. The endpoints include a set of tokens, namely , server.port , and context.root . When a SWF is loaded in a browser, as happens with all Flex applications, these tokens are replaced with the correct values, and the endpoints are configured properly. In AIR and even with RTMP channels (in RTMP, server.port needs a specific port number definition), these tokens are not resolved automatically, and so channels don’t work as expected, if configured using tokens.To test a channel, it may a good idea to try and access the endpoint URL with the browser and see whether you get a success message, such as 200 OK , or not. Where required, channels could accept additional properties. As an example, a polling AMF channel defines the polling interval using proper-ti es. An i nteresti ng fact i s that property setti ngs can create enti rely di fferent channels. AMF and polling AMF channels have the same class for implementing the channels, but they have different sets of properties and therefore different behavior.Using services-config.xml , the channel configurations are done at compile time. It’s also possible to configure channels and associate them with destinations at run time. More information about config-uration at run time is covered in the section “Configuring at run time” later in this chapter.The third important common configuration pertains to security. Exhaustive and complex security defini-tions are possible with data services, but we will go with the defaults for now. We shall deal with security configurations in data services in the section “Additional useful data services tips” later in this chapter.Although this chapter has not exhaustively covered the configuration options, you know the basics of configuration by now. You will learn more about configuration as you explore the other topics that relate to data services.Our new focus is to get data services into action. The three configuration files, remoting-config.xml ,proxy-config.xml , and messaging-config.xml , configure services, so we will look at these in the next few sections as we implement such services using BlazeDS or LCDS.Calling remote methods and serializing objectsYou know AMF is an efficient binary protocol and a data service lets you exchange data between Flex and Java. Let’s dig deeper so you can see what you need to do to leverage this mechanism in your Flex appli cati on. Because “seei ng i s beli evi ng” and, li ke pi ctures, worki ng code speaks louder than words, we will first create a simple example application that will establish RPC over AMF using a data service. In this example, our data service is BlazeDS.A simple example in actionThe example application is fairly simple.It displays a list of people and the country they come from. A person is identified by an ID, first name, and last name. A country is identified by a name. The initial list is populated from an XML data file that has four names in it. A user is allowed to add names to the list and delete existing ones.To demonstrate data services and remoting, the list and the methods to manipulate the list are kept on the server. These remote Java objects and their methods are accessed from a Flex client.We create this example using Flex Builder 3, but we could also do without it and compile directly using mxmlc , the command-l i ne comp i ler, or use Flex Ant tasks, ava i lable from w i th i n Ecl ipse. The 266command-line compiler and the Flex Ant tasks are available free of charge. The command-line com-piler comes bundled with the free Flex 3 SDK. The Flex Ant tasks software bundle can be downloadedfrom /wiki/index.php/Flex_Ant_Tasks.As a first step, we create a new Flex project, choose Web application as the application type and J2EEas the server technology. We name this project VerySimpleRemotingExample. Figure 7-3 shows these settings in the New Flex Project dialog.Figure 7-3. The initial screen for new Flex project creation in Flex Builder 3You will see that Flex Builder offers only two choices for a data service, namely LifeCycle Data Servicesand ColdFusion Flash Remoting. At first, this often causes confusion among developers, when using BlazeDS. Choose LifeCycle Data Services as the option in the current dialog box when using BlazeDS. Inthe next dialog box, you will have an opportunity to point to either the BlazeDS WAR or the BlazeDS directories, deployed on your application server.In the very first screen, a choice is offered to create a combined Java/Flex project using WTP. WTP,which stands for Web Tools Platform, is the set of tools available within Eclipse to create Java web applications. The WTP project is hosted at /webtools/. You can go to the project page to get more information on WTP.The “data services” software available for the Flex framework consists of web applications that run ina web container. Any custom logic you write with the data services either will be part of a web appli-cation or will be accessed from a web application. Therefore, if you are starting from scratch, choos-ing to create a joint project is often useful. If your Java-side application already exists, as in the case of267。

myflex

myflex

FLEX与C#、PHP、JAVA语言通信全面解析以下介绍几种最为常见和实用的FLEX与现有开发语言通信的方法:1.C#2.PHP3.JAVA1.Flex与C#通信(.net开发中常用)Flex端代码:public static function SendMessage(objXML:XML,objResultHandle:Function):void {var objHttpService:HTTPService = new HTTPService();objHttpService.url = "http://localhost:8085/upfiledata.aspx"; //发送到的C#页面objHttpService.resultFormat = "e4x";objHttpService.addEventListener(ResultEvent.RESULT,objResultHandle);objHttpService.method = "POST";objHttpService.contentType = "application/xml";objHttpService.send(objXML); //objXML 要发送的数据}public function objResultHandle(evt:ResultEvent):void{evt //接收到的数据}C#端:protected void Page_Load(object sender, EventArgs e){XmlDocument objProtocolDom = new XmlDocument();objProtocolDom.Load(Request.InputStream); //objProtocolDom接收来自Flex端所发送的数据流Response.ContentType = "text/xml";Response.Write(objResultDom.OuterXml); //向Flex端下发数据流}2.Flex与php通信Flex代码:<?xml version="1.0" encoding="utf-8"?><mx:Application xmlns:mx="/2006/mxml"creationComplete="onInit()" xmlns="*" layout="absolute"backgroundGradientColors="[#ffffff, #c0c0c0]"><mx:Script><![CDATA[public function onInit():void{userRequest.send();}]]></mx:Script><mx:HTTPService id="userRequest" url="request.php" useProxy="false"method="POST"><mx:request xmlns=""><username>{username.text}</username><emailaddress>{emailaddress.text}</emailaddr ess></mx:request></mx:HTTPService><mx:Form x="22" y="10" width="356"><mx:HBox><mx:Label text="Username"/><mx:T extInput id="username"/></mx:HBox><mx:HBox><mx:Label text="Email Address"/><mx:T extInput id="emailaddress"/></mx:HBox><mx:Button label="Submit" click="userRequest.send()"/></mx:Form><mx:DataGrid id="dgUserRequest" x="22" y="128"dataProvider="{er}"><mx:columns><mx:DataGridColumn headerText="User ID" dataField="userid"/><mx:DataGridColumn headerText="User Name" dataField="username"/> </mx:columns></mx:DataGrid><mx:T extInput x="22" y="292" id="selectedemailaddress"text="{dgUserRequest.selectedItem.emailaddress}"/></mx:Application>php代码:<?php/* Thanks to Pete Mackie for the code below */Define(’DATABASE_SERVER’, ’localhost’);Define(’DATABASE_USERNAME’, ’root’);Define(’DATABASE_PASSWORD’, ’root’);Define(’DATABASE_NAME’, ’flextest’);# Connect to the database$mysqli = new mysqli(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME);# Check connectionif (mysqli_connect_errno()) {printf("MySQL connect failed: %s\n", mysqli_connect_error());exit();}# Quote variable to make safefunction quote_smart($value) {global $mysqli;# Stripslashesif (get_magic_quotes_gpc())$value = stripslashes($value);# Quote if not integerif (!is_numeric($value))$value = $mysqli->real_escape_string($value);return $value;}if (!empty($_POST) && $_SERVER[’REQUEST_METHOD’] == ’POST’) { if ($_POST[’emailaddress’] && $_POST[’username’]) {# Add the user$query = sprintf("Insert INTO users VALUES (’’, ’%s’, ’%s’)",quote_smart($_POST[’username’]), quote_smart($_POST[’emailaddress’]));if (!@$mysqli->query($query)) {printf("’flextest’ user database query insert error: %s\n", $mysqli->error);$mysqli->close();exit();}}}# Return a list of all the usersif (!$result=@$mysqli->query("Select * from users")) {printf("’flextest’ user database query select error: %s\n", $mysqli->error);$mysqli->close();exit();}$xml_return = "<users>";while ($user = mysqli_fetch_array($result, MYSQLI_ASSOC)) {$xml_return .="<user><userid>".$user[’userid’]."</userid><username>".$user[’username’]."</usernam e><emailaddress>".$user[’emailaddress’]."</emailaddress></user>\n";}$xml_return.= "</users>";$mysqli->close();echo $xml_return;?>3.FLEX与JAVA之间的通信这里介绍一种方法:使用BlazeDS实现Java和Flex通信BlazeDS 是一个基于服务器的Java 远程控制(remoting) 和Web 消息传递(messaging) 技术,它能够使得后端的Java 应用程序和运行在浏览器上的Adobe Flex 应用程序相互通信。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Flex与Java通信之HttpService方式Flex用RemoteObject方式与Java通信是最常用的方式,这是一种最直观的方式。

当然Flex也可以用HttpService与服务器类如servlet通信,这也是本次学习的重点。

这次学习是在上节的基础上进行的。

本节学习用到的LoginEvent.as,LoginModule.mxml文件代码如上节所示。

好了,新建一个servlet类LoginServlet.java,代码如下所示:[java]view plaincopyprint?1.package com.yqsn.servlet;2.3.4.import java.io.IOException;5.import java.io.PrintWriter;6.7.import javax.servlet.ServletException;8.import javax.servlet.http.HttpServlet;9.import javax.servlet.http.HttpServletRequest;10.import javax.servlet.http.HttpServletResponse;11.12.public class LoginServlet extends HttpServlet {13.@Override14.protected void service(HttpServletRequest req, HttpServletResponse resp)15.throws ServletException, IOException {16.// TODO Auto-generatedmethod stub17. req.setCharacterEncoding("utf-8");18. resp.setCharacterEncoding("utf-8");19. PrintWriter out=resp.getWriter();20. String username=req.getParameter("username");21. String passworld=req.getParameter("passworld");22.//System.out.println(username+":"+passworld);23.if(username.equals("admin")&& passworld.equals("123")){24. out.print(true);25. }else{26. out.print(false);27. }28. }29.}这个servlet在web.xml中的配置如下所示:[html]view plaincopyprint?1.<servlet>2.<servlet-name>LoginServlet</servlet-name>3.<servlet-class>com.yqsn.servlet.LoginServlet</servlet-class>4.</servlet>5.<servlet-mapping>6.<servlet-name>LoginServlet</servlet-name>7.<url-pattern>/LoginServlet</url-pattern>8.</servlet-mapping>将MyEclipse切换到flash视图,新建一个application文件HttpServiceDemo.mxml,代码如下所示:[html]view plaincopyprint?1.<?xmlversion xmlversion="1.0"encoding="utf-8"?>2.<s:Application xmlns:fx="/mxml/2009"3.xmlns:s="library:///flex/spark"4.xmlns:mx="library:///flex/mx"minWidth="955"minHeight="600">5.6.<fx:Script>7.<![CDATA[8. import com.flex.ases.LoginEvent;9. import com.flex.ases.LoginMess;10. import com.flex.module.LoginModule;11.12. import mx.controls.Alert;13. import mx.managers.PopUpManager;14. import mx.rpc.events.FaultEvent;15. import mx.rpc.events.ResultEvent;16. private var loginModule:LoginModule=new LoginModule();17. [Bindable]18. private var username:String;19. [Bindable]20. private varpassworld:String;21. protected function login_clickHandler(event:MouseEvent):void22. {23. // TODOAuto-generated method stub24. PopUpManager.addPopUp(loginModule,this,true);25. PopUpManager.centerPopUp(this.loginModule);26. loginModule.addEventListener(LoginEvent.LOGIN_EVENT,loginHander);27. }28. public function loginHander(event:LoginEvent):void{29. //varobj:Object=event.loginMess as Object;30. username=event.loginMess['username'];31. passworld=event.loginMess['passworld'];32. httpServiceSend.send();33. }34.35. protected function httpServiceSend_faultHandler(event:FaultEvent):void36. {37. // TODOAuto-generated method stub38. Alert.show(event.fault.message as String,"提示");39.40. }41.42. protected function httpServiceSend_resultHandler(event:ResultEvent):void43. {44. // TODOAuto-generated method stub45. var result:Boolean=event.result as Boolean;46. if(result){47. Alert.show(username+",欢迎您回来!","提示");48. aaa.text=username+",欢迎您回来!";49. bel="";50. bbb.text="";51.52. }else{53. Alert.show("对不起,用户名或密码不存在!","提示");54. }55. //Alert.show("成功了!");56. }57.58. ]]>59.</fx:Script>60.61.<fx:Declarations>62.<!-- Place non-visualelements (e.g., services, value objects) here -->63.<s:HTTPService id="httpServiceSend"url="http://localhost:8000/JavaAndFlexDemo/LoginServlet"useProxy="false"fault="httpServiceSend_faultHandler(event)"result="http ServiceSend_resultHandler(event)">64.<s:request>65.<username>{username}</username>66.<passworld>{passworld}</passworld>67.</s:request>68.</s:HTTPService>69.</fx:Declarations>70.<s:Label x="200"y="150"width="182"height="27"fontSize="18"id="aaa"text="您还没有登陆,现在就"verticalAlign="middle"/>71.<mx:LinkButton x="393"y="150"width="57"height="27"label="登陆"id="login"fontSize="18"click="login_clickHandler(event)"/>72.<s:Label x="459"y="150"width="37"height="27"id="bbb"fontSize="18"text="吧!"verticalAlign="middle"/>73.</s:Application>从代码中我们可以看出,我们先定义一个HttpServlet发送请求httpServiceSend,然后通过下面这种方式存值:[html]view plaincopyprint?1.<s:request>2.<username>{username}</username>3.<passworld>{passworld}</passworld>4.</s:request>这种方式很简单,我们在后台通过request. getParameter(“参数名”)取值就可以了,当然我们也可以在loginHander(event:LoginEvent)函数中通过下面方式存值并发送请求:[html]view plaincopyprint?1.public functionloginHander(event:LoginEvent):void{2. //varobj:Object=event.loginMess as Object;ername=event.loginMess['username'];4.passworld=event.loginMess['passworld'];5. var obj:Object=new Object;ername=username;7.obj.passworld=passworld;8. httpServiceSend.send(obj);9. }运行结果是一样的,你可以试试。

相关文档
最新文档