Getting Flex 3 talking to Java via JSON
packagecom.giantflyingsaucer;
importjava.io.*;
importjava.io.PrintWriter;
importjavax.servlet.*;
importjavax.servlet.http.*;
importorg.json.simple.*;
publicclass MessageServlet extendsHttpServlet
{
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException
{
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
JSONObject jsonObject = newJSONObject();
try
{
String strJSON = null;
JSONObject myObject = null;
if(request.getParameter("myObject") != null)
{
strJSON = request.getParameter("myObject");
Object obj = JSONValue.parse(strJSON);
myObject = (JSONObject)obj;
String value1 = myObject.get("value1").toString();
String value2 = myObject.get("value2").toString();
jsonObject.put("value1","Hello: " + value1);
jsonObject.put("value2","Hello: " + value2);
}
else
{
jsonObject.put("ERROR","Invalid JSON");
}
}
finally
{
out.print(jsonObject);
out.flush();
out.close();
}
}
}
Here is a quick and easy way to pass JSON to and from Flex 3 and a Java Servlet. First off you need to grab the AS3CoreLib from Google
Code. Once you have the as3corelib you’ll want to make it so you can use the contents of “corelib/src” from within your Flex project. I imported it into Flex Builder 3 (beta 2). For the Java part of it you can use whatever you like, I like to use Eclipse with
the MyEclipseIDEplugin and then use their “Web Project” wizard
to get my web app going. I used Tomcat 6 for the servlet container and added a single servlet to the project.
For the Java servlet to understand the JSON I grabbed the “Simple JSON” library here.
Its very easy to use, just import it into your Eclipse web project project (or whatever your using). Here is the servlet’s code:
Now for the Flex code:
<?xml version="1.0"encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"layout="absolute">
<mx:Script>
<![CDATA[
importcom.adobe.serialization.json.JSON;
importflash.events.*;
importflash.net.*;
publicfunction runMe():void
{
varloader:URLLoader = newURLLoader();
varheader1:URLRequestHeader = null;
varrequester:URLRequest = newURLRequest();
header1 = newURLRequestHeader("pragma","no-cache");
requester.requestHeaders.push(header1);
requester.method = URLRequestMethod.POST;
configureListeners(loader);
loader.dataFormat = URLLoaderDataFormat.TEXT;
// Modify to your needs
requester.url = "http://localhost:8085/MessageServer/servlet/MessageServlet";
varobj:Object= newObject();
obj.value1 = "Bob";
obj.value2 = "Sandy";
varvariables:URLVariables = newURLVariables();
variables.myObject = JSON.encode(obj);
requester.data = variables;
loader.load(requester);
}
privatefunction configureListeners(dispatcher:IEventDispatcher):void
{
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
dispatcher.addEventListener(Event.OPEN, openHandler);
dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}
privatefunction completeHandler(event:Event):void
{
try
{
vartempLoader:URLLoader = URLLoader(event.target);
varobj:Object= JSON.decode(tempLoader.data);
trace("completeHandler: " + tempLoader.data);
trace(obj.value1);
trace(obj.value2);
}
catch(error:Error)
{
trace("completeHandler: " + error.toString());
}
}
privatefunction openHandler(event:Event):void
{
trace("openHandler: " + event);
}
privatefunction progressHandler(event:ProgressEvent):void
{
trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
}
privatefunction securityErrorHandler(event:SecurityErrorEvent):void
{
trace("securityErrorHandler: " + event);
}
privatefunction httpStatusHandler(event:HTTPStatusEvent):void
{
trace("httpStatusHandler: " + event);
}
privatefunction ioErrorHandler(event:IOErrorEvent):void
{
trace("ioErrorHandler: " + event);
}
]]>
</mx:Script>
<mx:Button x="19"y="10"label="Run Me" id="btnRunMe"click="runMe()"enabled="true"/>
</mx:Application>
You should see something like this:
openHandler:progressHandlerhttpStatusHandler:completeHandler:Hello:Hello: |
I also like to use Fiddler 2 to inspect whats going over
the wire. Firebug for Firefox I assume
would work as well. These tools can be very handy when you want to inspect whats going on – especially when you need to debug an issue.
Getting Flex 3 talking to Java via JSON的更多相关文章
- Flex使用Blazeds与Java交互及自定义对象转换详解-DATAGRID读取ORACLE数据
http://www.cnblogs.com/RocD-DuPeng/articles/1751040.html 一.建立Flex与Java交互的工程. 本文中讲到的交互是利用Blazeds的,因为这 ...
- Java集合 Json集合之间的转换
1. Java集合转换成Json集合 关键类:JSONArray jsonArray = JSONArray.fromObject(Object obj); 使用说明:将Java集合对象直接传进JSO ...
- Java对象 json之间的转换(json-lib)
在这里主要简单的介绍一下,如何使用json-lib这个工具包来完成Java对象(或集合)与json对象(或集合)之间的转换~ 1. Java对象转换成json(既创建json) 关键类:JSONObj ...
- Java 的 JSON 开源类库选择比较(zz)
在看了作者的介绍,然后我又到mvnrepository上去看了各个库的的使用数之后,发现只能在jackson和gson之间做选择. 以下是原文 有效选择七个关于Java的JSON开源类库 April ...
- java中json包的使用以及字符串,map,list,自定义对象之间的相互转换
做一个map和字符串的转换,需要导入这些jar包,这是最基本的一些jar包. 经过多方尝试得出结论入下: 首先导入基本包:json-lib-2.2.3-jdk15.jar 如果没有这个jar包,程序是 ...
- java系列--JSON数据的处理
http://blog.csdn.net/qh_java/article/details/38610599 http://www.cnblogs.com/lanxuezaipiao/archive/2 ...
- Java之JSON数据
特别注意:使用JSON前需要导包 操作步骤地址:http://blog.csdn.net/baidu_37107022/article/details/70876993 1.定义 JSON(JavaS ...
- JSON以及Java转换JSON的方法(前后端常用处理方法)
)); map.put("arr", new String[] { "a", "b" }); map.put("func" ...
- java处理json与对象的转化 递归
整个类是一个case,总结了我在使用java处理json的时候遇到的问题,还有级联关系的对象如何遍历,json和对象之间的转换! 对于对象json转换中遇到的问题我参考了一篇博客,http://blo ...
- Java JWT: JSON Web Token
Java JWT: JSON Web Token for Java and Android JJWT aims to be the easiest to use and understand libr ...
随机推荐
- 小tips:nodejs请求接口超时使用中间件connect-timeout实现自动超时机制
如果在请求中不设置超时时间,那么一直处理loading卡屏状态,使用connect-timeout来设置自动超时时间. 安装: npm install connect-timeout -S 如下例子: ...
- OData – 大杂烩
前言 本篇记入一些 OData 的小东西. Query string too long OData 使用 GET 请求,然后搭配 query string $filter, $select, $exp ...
- JavaScript Library – YouTube Embedded、YouTube Player API、YouTube Data API
YouTube Embed Video 参考: Embed videos & playlists 它和 Google Maps Embed 类似,是通过 iframe 完成的. <ifr ...
- 项目发布后项目时间和linux时间不一致
查阅了很多资料,本来总以为是项目的问题,启动前端,连接不同的后台,本地项目时间是正确的,部署到linux Docker容器就不行.很纳闷...... 基于以上,还是决定记下来,以便后来的人查阅,解决问 ...
- x64汇编——汇编指令
汇编指令 mov dest, src mov move的简称 将src的内容赋值给dest,类似于dest = src [地址值] 中扩号 [ ]里面放的都是内存地址 一个变量的地址值,是它所有字节地 ...
- MySQL配置缓存查询和维护
配置文件设置缓存 query_cache_size = 20M #缓存大小 query_cache_type = ON #开启缓存 table_cache=256 #用于限制缓存表的最大数目,如果当前 ...
- 【赵渝强老师】使用MongoDB的Web控制台
MongoDB可以通过web界面监控数据库,默认情况下该选项是关闭的,需要在启动的时候开启.启用web 控制台,需要在启动mongodb的时候,加上:--httpinterface 启动MongoDB ...
- 10款好用的开源 HarmonyOS 工具库
大家好,我是 V 哥,今天给大家分享10款好用的 HarmonyOS的工具库,在开发鸿蒙应用时可以用下,好用的工具可以简化代码,让你写出优雅的应用来.废话不多说,马上开整. 1. efTool efT ...
- 利用cv2.dilate对图像进行膨胀
cv2.getStructuringElement(cv2.MORPH_RECT, (7,7))介绍,请看这个博客.我简要说一下cv2.getStructuringElement,可用于构造一个特定大 ...
- 精彩回顾|【ACDU 中国行·杭州站】数据库主题交流活动成功举办!
8月19日下午,[ACDU 中国行·杭州站]在杭州西溪万怡酒店圆满落下帷幕.本次活动由中国数据库联盟(ACDU)联合墨天轮社区主办,蚂蚁集团 OceanBase 及亚信科技 AntDB 赞助支持.六位 ...