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. 啥是Session?

    什么是 Session 会话? 1.Session 就一个接口(HttpSession). 2.Session 就是会话.它是用来维护一个客户端和服务器之间关联的一种技术. 3.每个客户端都有自己的一 ...

  2. 利用分布式锁在ASP.NET Core中实现防抖

    前言 在 Web 应用开发过程中,防抖(Debounce) 是确保同一操作在短时间内不会被重复触发的一种有效手段.常见的场景包括防止用户在短时间内重复提交表单,或者避免多次点击按钮导致后台服务执行多次 ...

  3. attention, transformers

    这啥呀,慢慢啃 Attention 最初来源于 NLP 机器翻译的 Sequence to Sequence 模型,早先的encoder-decoder结构随着句子长度增加翻译性能会下降,因为模型记不 ...

  4. C++ 高效使用智能指针的8个建议

    C++ 高效使用智能指针的8个建议 前言:智能指针是C++11提供的新特性,它基于RAII实现,可以自动管理内存资源,避免内存泄漏的发生,但是智能指针也并不是万能的,如果不正确使用智能指针,也会导致内 ...

  5. postgresql数据库中 JSON 字段 replace

    一.需求 postgresql 数据库,需要将某些表中的json字段的数据进行替换. 二.做法 思路:将json字段转为text,然后调用replace函数后,将text再转为json update ...

  6. C#上位机与PLC通信心跳的实现方法

    -Begin- 大家好!我是付工.众所周知,在工业自动化控制系统中,上位机与下位机之间的通信是实现自动化生产的关键环节之一.为了确保通信的稳定性和可靠性,我们通用会采用一种被称为[心跳机制]的方法,它 ...

  7. Java项目笔记(四)

    1.包装类判断是否相等时,建议用equals 而不是 == 号 2.+= 默认包含了强制类型转换,单纯的s = s+1;编译是无法通过的,因为1属于int类型,必须显示声明强制类型转换 short s ...

  8. llama.cpp推理流程和常用函数介绍

    llama.cpp是一个高性能的CPU/GPU大语言模型推理框架,适用于消费级设备或边缘设备.开发者可以通过工具将各类开源大语言模型转换并量化成gguf格式的文件,然后通过llama.cpp实现本地推 ...

  9. Android Qcom USB Driver学习(十四)

    UDC-Gadget UDC:(USB Device Controller)用于管理和控制USB设备与主机之间的通信. Gadget:Android在此层实现了adb,mtp(Media Transf ...

  10. iOS中异常处理机制使用小结

    在iOS开发中经常会由于数组越界,添加数据为空,通信或者文件错误,内存溢出导致程序终端运行而引入异常处理机制.常用的处理方式是try catch机制.不过有几个专业术语需要解释,异常句柄.异常处理域断 ...