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 ...
随机推荐
- Redis实战11-实现优惠券秒杀下单
本篇,咱们来实现优惠券秒杀下单功能.通过本篇学习,我们将会有如下收获: 1:优惠券领券业务逻辑: 2:分析在高并发情况下,出现超卖问题产生的原因: 3:解决超卖问题两种方案:版本号法及CAS法 4:乐 ...
- spark 先groupby 再从每个group里面选top n
import spark.implicits._ val simpleData = Seq(("James","Sales","NY",90 ...
- 总结篇3:redis 典型缓存架构设计问题及性能优化
聊聊对于缓存预热.缓存穿透.缓存雪崩.缓存击穿.缓存更新.缓存降级的定义理解 缓存穿透 定义 当查询Redis中没有的数据时,该查询会下沉到数据库层,同时数据库层也没有该数据,当这种情况大量出现或被恶 ...
- kubernetes重新初始化“[ERROR DirAvailable--var-lib-etcd]”
[root@master01 ~]# kubeadm init --config /root/kubeadm-config.yaml --upload-certs [init] Using Kuber ...
- 全网最适合入门的面向对象编程教程:46 Python函数方法与接口-函数与事件驱动框架
全网最适合入门的面向对象编程教程:46 Python 函数方法与接口-函数与事件驱动框架 摘要: 函数是 Python 中的一等公民,是一种可重用的代码块,用于封装特定的逻辑:事件驱动框架是一种编程模 ...
- WebRTC 简单入门与实践
一.前言 WebRTC 技术已经广泛在各个行业及场景中被应用,但对多数开发者来说,实时音视频及相关技术却是比较不常接触到的. 做为一名 Web 开发者,WebRTC 这块的概念着实花了不少时间才搞明白 ...
- Naming Conversion & Case Style 命名规范
前言 写代码有 2 个点很重要 第一是表达 (不要词不达意) 要达到这点, 就要多参考其它人如何表达. 第二是一致性 (一样的东西就用一样的写法) 要达到这点就要建立规范 以前的笔记 命名规范 nam ...
- Epic Games Launcher 提示 应用程序无法正常启动(0xc000007b)
事件起因: 在给某同事安装Epic Games Launcher报错, 提示 应用程序无法正常启动(0xc000007b) 解决办法: 用DirectX修复工具扫一下,修复一下C++插件,一般是由于 ...
- Java日期时间API系列31-----Jdk8中java.time包中的新的日期时间API类,时间戳的获取方式对比、转换和使用。
时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数,是所有时间的基础,其他时间可以通过时间戳转换得到.Java中本来已经有相关获取时间戳的方法,Java8后增加新的类In ...
- 简化版本的redis配置文件
# bind 192.168.1.100 10.0.0.1 # bind 127.0.0.1 ::1 #bind 127.0.0.1 protected-mode no port 6379 tcp-b ...