Monday, March 23, 2009

Using RemoteObject in tomcat webserver

This is a sample application which tells how to communicate between Flex and Java using RemoteObject.

Prerequisites,
  • Tomcat webserver here. See if we download BlazeDS turnkey there is tomcat in itself, but we need to run our application in the existing server.
  • BlazeDS  here. Why BlazeDS is to get the jar files and the xml files.
  • Adobe Flex Builder, you can download the trail version here
  • Java here

1. First we discuss about creating a Java application which serves the request to the Flex application.

Here this is a simple java program.

public class JavaFlex
{
public JavaFlex()
{
}

public String sayHello()
{
return "Hello Flex";
}
}

The funtion sayHello() is called by flex application which inturn returns the string to the flex call.

2. Create an application in the tomcat server and copy the files from BlazeDS/WEB-INF/flex, libs, web.xml in to your newly created application/WEB-INF folder in the tomcat server and create an empty classes folder inside.

3. Add a destination in the remoting-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<service id="remoting-service" class="flex.messaging.services.RemotingService">

<adapters>

<adapter-definition id="java-object" class="flex.messaging.services.remoting.adapters.JavaAdapter" default="true"/>

</adapters>

<default-channels>

<channel ref="my-amf"/>

</default-channels>

<destination id="flex-java">

<properties>

<source>JavaFlex</source>

</properties>

</destination>

</service>

4. Compile the java application and place it in the WEB-INF\classes, if the java application is inside the package, 

give the appropriate structure in the destination source.

5. Create the Flex J2EE application, "check creating Flex J2EE application in Adobe Flex Docs"

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">

<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
/* */
private function onResult( event:ResultEvent ):void
{
Alert.show(event.result.toString())
}

/* */
private function onFault( event:FaultEvent ):void
{
Alert.show('Fault');
}

]]>
</mx:Script>
<mx:RemoteObject
destination="flex-java"
id="rem"
showBusyCursor="true">
<mx:method name="sayHello" result="onResult( event )" fault="onFault( event )" />
</mx:RemoteObject>
<mx:Button label="Call Java" click="rem.sayHello.send()" /> 
</mx:Application>

Start the tomcat server and run the flex application, 
click the button, an alert shown with the string "Hello"

No comments:

Post a Comment