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:

Very simplified 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>

Ok the Flex UI isn’t going to win any awards – but we just want the basics of how to get this working. Make sure when you run the Flex project you do so in debug mode so you can see the “trace” results since that is where all the info is being dumped.

You should see something like this:

openHandler:
[Event type="open" bubbles=false cancelable=false eventPhase=2]
progressHandler
loaded:47 total: 0
httpStatusHandler:
[HTTPStatusEvent type="httpStatus" bubbles=false cancelable=false eventPhase=2 status=200]
completeHandler:
{"value1":"Hello: Bob","value2":"Hello: Sandy"}
Hello:
Bob
Hello:
Sandy

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的更多相关文章

  1. Flex使用Blazeds与Java交互及自定义对象转换详解-DATAGRID读取ORACLE数据

    http://www.cnblogs.com/RocD-DuPeng/articles/1751040.html 一.建立Flex与Java交互的工程. 本文中讲到的交互是利用Blazeds的,因为这 ...

  2. Java集合 Json集合之间的转换

    1. Java集合转换成Json集合 关键类:JSONArray jsonArray = JSONArray.fromObject(Object obj); 使用说明:将Java集合对象直接传进JSO ...

  3. Java对象 json之间的转换(json-lib)

    在这里主要简单的介绍一下,如何使用json-lib这个工具包来完成Java对象(或集合)与json对象(或集合)之间的转换~ 1. Java对象转换成json(既创建json) 关键类:JSONObj ...

  4. Java 的 JSON 开源类库选择比较(zz)

    在看了作者的介绍,然后我又到mvnrepository上去看了各个库的的使用数之后,发现只能在jackson和gson之间做选择. 以下是原文 有效选择七个关于Java的JSON开源类库 April  ...

  5. java中json包的使用以及字符串,map,list,自定义对象之间的相互转换

    做一个map和字符串的转换,需要导入这些jar包,这是最基本的一些jar包. 经过多方尝试得出结论入下: 首先导入基本包:json-lib-2.2.3-jdk15.jar 如果没有这个jar包,程序是 ...

  6. java系列--JSON数据的处理

    http://blog.csdn.net/qh_java/article/details/38610599 http://www.cnblogs.com/lanxuezaipiao/archive/2 ...

  7. Java之JSON数据

    特别注意:使用JSON前需要导包 操作步骤地址:http://blog.csdn.net/baidu_37107022/article/details/70876993 1.定义 JSON(JavaS ...

  8. JSON以及Java转换JSON的方法(前后端常用处理方法)

    )); map.put("arr", new String[] { "a", "b" }); map.put("func" ...

  9. java处理json与对象的转化 递归

    整个类是一个case,总结了我在使用java处理json的时候遇到的问题,还有级联关系的对象如何遍历,json和对象之间的转换! 对于对象json转换中遇到的问题我参考了一篇博客,http://blo ...

  10. 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 ...

随机推荐

  1. vue 中 elementUI el-table 实现滚动加载

    vue 中 elementUI el-table 实现滚动加载 一.需求 vue 中 elementUI el-table 实现滚动加载,场景:当表格需要显示大量数据时,又想通过一页来进行展示数据. ...

  2. ZEGO 自研客户端配置管理系统 —— 云控

    一.常规客户端配置的弊端 客户端配置信息通常会通过一个静态文件进行管理,或存放在本地或者通过远程获取.存在本地最大的问题是不易更新,所以通常做法是通过远程获取. 我们通过两种常见的场景来看看静态文件管 ...

  3. DOM & BOM – 用 Canvas 修图

    前言 以前有写过一篇关于 canvas 处理图片的文章. 非常乱, 这篇做一个整理. 参考 Stack Overflow – HTML5 Canvas Rotate Image Stack Overf ...

  4. Java获取Object中Value的方法

    在Java中,获取对象(Object)中的值通常依赖于对象的类型以及我们希望访问的属性.由于Java是一种静态类型语言,直接从一个Object类型中访问属性是不可能的,因为Object是所有类的超类, ...

  5. 2024.09.18初赛模拟MX-S/P6029记录

    MX-S 太简单了,没啥难度.\yiw $ 1, 3, 5, 7, 9 $ 的二叉搜索树棵数是卡特兰数. P6029 题意 给定一张有 $ n $ 个点,$ m $ 条边的图.可以任意交换途中两条边的 ...

  6. Maya 2019.2 Mtoa 无法正常加载并报错

    事件起因: 在开始安装 Maya2019.2 时自动安装的 Mtoa 的版本为 5.3.1,但是在插件管理器里无法启用插件,于是乎去网上下了一个低的版本 5.1.1,虽然可以使用但是渲染出来的东西不能 ...

  7. 智能化IT运维平台建设方案,基于智和信通运维体系的高敏捷二次开发

    随着企业信息进程不断加速,运维人员需要面对越来越复杂的业务和越来越多样化的用户需求,不断扩展的应用需要越来越合理的模式.越来越智能的工具来保障运维能灵活便捷.安全稳定地开展.企业网络规模的不断扩大,从 ...

  8. 墨天轮沙龙 | 麦杰科技卢学东:openPlant 实时数据库系统及应用

    在8月24日举办的[墨天轮数据库沙龙第九期-工业实时数据库专场]中,麦杰科技创始人 卢学东分享了<麦杰openPlant实时数据库系统及应用>主题演讲,本文为整理内容. 导读 工业互联网推 ...

  9. 5.flask 源码解析:请求

    目录 一.flask 源码解析:请求 1.1 简介 1.2 请求 Flask 源码分析完整教程目录:https://www.cnblogs.com/nickchen121/p/14763457.htm ...

  10. 「模拟赛」CSP-S 模拟 11(T2 超详细)

    比赛链接 A.玩水 (water) 签到.发现如果要找两条路径的话,能找到的充要条件是存在一个点的上方和左方的字母相同.(即使两条走过的点截然不同的路径也符合,这时终点会成为这个点). 即存在一个位置 ...