Login | Register
Getting Across to Flash with Java

Getting Across to Flash with Java

If you work in web applications, it's just a matter of time until someone suggests, "why don't we use Flash?" With Macromedia Flash, you can create juicy, enjoyable interfaces for your users, with a unique branded appearance. Moreover, Macromedia's tools and the Flash creation metaphors are understood by more graphic artists and interface designers than other options.

By Nancy Hickman For an interface, Flash can be a great option; however, for the backend, it's not an option to replace business logic, query management, and security. For robust performance and enterprise capabilities, you need Java. Both Flash and Java promote themselves as a cross-device, cross platform solutions, so they are natural partners. Connecting the two is often up to the Java developer, and to start, you need to know your options on how to get across to Flash.

First, here's a bit about Flash. For application developers, Flash offers a scripting EMCA-based language called ActionScript and a palette of components. The components aren't as robust as Swing, but they cover the basics for common interfaces. Some Flash components are data-aware, and more are offered in the newest version, Flash MX 2004. Developers can write functions and attach them to component events, much like the listener model in Java.

In Flash MX 2004, for the first time, Macromedia offers two versions of their Flash development tool: Flash and Flash Professional. The newest Flash 7 player runs Flash movies developed with either tool. Flash Professional provides extras such as data and web service binding, video integration improvements, and device emulators. Flash Professional also offers a new metaphor for designers in addition to its animation frame-based timeline: form or screen based design, which will be helpful to application designers.

Both Flash versions can call Java code contained in JSPs, servlets, beans, or published web services. By default, the Java code must be in the same subdomain as the Flash movie, but with the new version of Flash, you can supply an xml policy file to allow other locations. Of course, the backend Java code can contact other domains.

Java developers using Flash need to know how to do a few common tasks: receiving and sending Flash data and dealing with data type issues. Getting information out of a form-like interface is easy with Flash, and sending information in that interface is often as simple as printing to an out object. Here are some methods to send and receive Flash data from Java: from simplest to complex modes.

URL Encoding
Outbound, URL encoding is the simplest model of calling a JSP or servlet. On an event in Flash, you can send a URL with parameters encoded in strings. On the Flash side, you call the URL:

getURL("http://www.server.com/thequiz.jsp?question1=Yes&question2=No", "_blank","POST");

On the java side, you simply parse the request parameters and process them. A drawback is that URL requests need somewhere to load a response page, and it attempts to load it in the same window, in a frame, or in another specified window. You may not want this behavior in your design. It could be ideal to popup a window or to be the final step in an application. For example, for a series of Flash frames, you could save the user's work, and then commit them at the end with a call to a JSP. However, if the Flash session must reload, it loses the user's work.

LoadVars Object
As an improvement over straight URL encoding, you can use a LoadVars object in the ActionScripting model to call Java code. It's a real exchange with a Java backend, allowing sending and receiving. With a LoadVars object, you still have to follow URL encoding, and it's an asynchronous HTTP transmission, but it doesn't unload your Flash movie. You can use a GET or POST. Here's what the ActionScript would look like in a situation where a JSP is called with a LoadVars object. The JSP will make a query based on a showcase id number and return the results to an ActionScript called capture_desc.

showcase_desc = new LoadVars();
showcase_desc.showcase_id = showcase_id;
showcase_desc.sendAndLoad("fillShowcasedesc.jsp", showcase_desc, "POST");
showcase_desc.onLoad = capture_desc;

On the java side, the code simply pulls off the parameters on the request object. Session can be maintained if you use session objects in Java. All you have to do is have Java code waiting to collect the data. Here's the line for the JSP called above:


String showcase_id = request.getParameter("showcase_id");

Then you can write data back out to Flash:

out.println("&description" + "=" + showcase_desc);

Is it that simple? Yes, it is. On the Flash side, you can get a response back on the LoadVars object on the success of the transaction and handle it, which is a real exchange with Java backend. However, the Flash interface waits for the HTTP response, which can cause apparent hesitation. If you are loading the Flash interface with data, it's helpful to change the Flash interface to indicate "loading" before requesting making the LoadVars request. The returned data to Flash can be loaded into the interface.

function capture_desc(success)
  if (success == true) {
  showcase_description = "";
  showcase_description = showcase_desc.description;

XML Objects
In the same vein as LoadVars, you can send or request XML and manage it through an ActionScript object. Flash can read XML as, basically, a long string set on the response object or XML files. Flash doesn't have a sophisticated parser or verifier, and you have to write ActionScript to load the XML information, but it can be quite handy. In the case of list components, they can be easier to load with an XML object than a LoadVars object. For example, you can format the rows returned on a query as XML to load components.

function capture_showcase(success) {
	if (success == true) {
		mainTag = new XML();
		elementTag = new XML();
		dataList = new Array();

		elementList = new Array();
		mainTag = this.firstChild;
		if (mainTag.nodeName == "dataSet") {
			dataList = mainTag.childNodes;
			for (i=0; i<=dataList.length; i++) {
				if (dataList.nodeName == "data") {

					elementList = dataList.childNodes;
					for (j=0; j<=elementList.length; j++) {
						elementTag = elementList[j];
						elementType = elementTag.nodeName;
						if (elementType == "showcase_id") {
							ID = elementTag.firstChild.nodeValue;

						if (elementType == "showcase_title") {
							Show_Title = elementTag.firstChild.nodeValue;

Again, the request is an HTTP request. In Flash Professional, you can use an XML connector object to bind XML sources with components. When you use XML objects, the Java code writes out string data. No header on the XML is used. Of course, if you send and receive XML, the Java code takes on the larger role to correct the format and verify it, and in the case of my example, there's more code that is not shown that handled a query and a resultset.

out.print( "" );
out.print( "" + title + "" );
out.print( "" + showcase_id + "");
out.print( "");

XML Sockets
Instead of using an XML object through HTTP, you can use a XML-socket persistent connection. This connection is ideal for chat or gaming applications. On the Flash side, you create an XMLSocket object, and when it receives XML, the onXML event is triggered.

myConn = new XMLSocket;
myConn.connect("http://www.myflashserver.com", 1025);
myConn.onXML = processXML;

In the above case, you'd write an ActiveScript function called processXML that would interpret the incoming XML document.

On the java side, it's easy to communicate through XML Sockets. The code is the same as any simple socket application: create a socket, through port 1024 or higher, and an inputstream and read your data into a stringbuffer: send data out on an outputstream through that socket. The XML documents don't use a DTD. The Flash XML documents are like a long string: it skips the XML header, and the end of file marker is a single byte zero.

XML Sockets do have a couple of drawbacks. The XML transfer is faster this way, but it's the least secure method of communication. Not only that, some firewalls will not allow this sort of connection. If you want security with more speed than LoadVars, you should consider Remoting.

All of the previous methods basically transfer string information. If you want to transfer more sophisticated data with faster responses, Flash offers a protocol called Remoting. With Remoting, you can directly call methods on Java objects and transfer a variety of data types.

Remoting uses HTTP or HTTPS, but Flash uses a proprietary, optimized, binary format, AMF or Action Media Format. To use Remoting, the Flash developer must install additional ActionScript libraries, which are available for free from Macromedia. (The new version of Flash Professional comes with these libraries.)

On the server side, a "gateway" servlet must be installed. (Don't forget to configure a web.xml file.) Macromedia's JRun servers have Remoting installed, but you can install Remoting with any Java server. The gateway servlet acts as a factory for connections to Java objects. The gateway maps incoming data to target Java data types or to an ASObject, and maps outgoing data to target ActionScript data types or to an ASObject. You can use these mappings or you can create an ASObject and handle getting and setting data yourself. You can include Java objects on the ASObjects, but since it is serialized, you can't have objects inside objects that you include. Connecting to Flash through Remoting is simple; the task of designing how you want to handle data casting would be where you'd spend the most time.

Object Mapping Chart
ActionScript data type -> Java data type
Number (primitive data type) -> Double
Boolean (primitive data type) -> Boolean
String -> String
ActionScript (AS) -> object Map
null -> null
undefined -> null
Ordered array -> ArrayList
Named array -> Map
Date object -> Date
XML object -> org.w3c.dom Document
RecordSet -> RowSet

On the Flash side, you have to include Remoting, and create a connection, get a service object, and call the java method.

# include "NetServices.as";
var gatewayConn = Netservices.createGatewayConnection();
var service = gatewayConn.getService("com.mycompany.myJava", this);
service.getCustomers(new handleCustomers());

Results are sent to an ActionScript function, in this case called handleCustomers(), that you would write on the Flash side.

Your Java code is simple. You just import the ASObject or implement serializable on your class.

import flashgateway.io.ASObject;
public class service {
	public ASObject getCustomers(){
		ASObject cust = new ASObject("custList");
		cust.put("99", "Smith");
		cust.put("101", "Anderson");
		return cust;

With Remoting, you can use HTTPS for security purposes, but Remoting can expose some security concerns, since it allows direct calls. To avoid problems, set up security policies on your Java classes to prevent wholesale access to your libraries.

Remoting makes development on the Flash side easier, because you can use an ActionScript extension called DataGlue to simply the task of binding and formatting data for the interface. With DataGlue, for example, you can bind recordset objects and its formatting to Flash interface components with a couple of lines of code. With the new Flash Professional 2004, Macromedia extends this idea into the authoring interface, by adding a feature that makes binding components to web services and XML sources as easy as filling out property sheets. In the Component Inspector, the Flash developer can use the Component Inspector and basically click through some tabbed dialog boxes and data bind interface components to published java web services or XML sources, instead of writing lines of ActionScript. They can use it tune the formatting too. This feature is available with or without Remoting. For the Java developer, it's a bit more work to create published web services, but it makes Java methods available to Flash development almost like a tag.

Remoting with Communication Server
If you use Remoting, you can enhance its performance by using Macromedia's Communication Server with it. The server is an additional product to purchase, but if you employ a lot of video and audio, it's worth it. The server offers the most efficient streaming of video and audio to Flash interfaces. On the data side, it caches and polls data for changes, so you'll see good performance improvements in reporting interfaces. The Java coding required is the same as Remoting without the Server, but you may want to revisit your security plans. The Communication Server uses a proprietary protocol: RTMP, which is a TCP/IP protocol, so you can't use HTTPS.

As you can see getting across to Flash with Java is so very easy, and using this combination a great example of MVC architecture. The first step is making a decision on how to connect, and I hope this article's been a good survey for you. There's been a lot of talk about using Coldfusion or PHP to do the job, but Java is a more robust language to architect a backend than PHP or Coldfusion tags. Also the Java APIs are cross platform, which allows you to grow into new markets. For example, as Flash's market continues to grow into the device area, Java's library support would be key to making cross-device Flash applications for hand-helds. Java and Flash are natural partners, and together will make a successful partnership in a growing number of application architectures.


Get new stories first

Click to follow us on Twitter!



No comments for this page.

Submit a comment

Only registered members can comment. Click here to login or here to register