Sunday, May 23, 2010

Flex Remoting with Java Part 2

In the last blog entry, I wrote about setting up a simple Flex Application and integrating it with Java so as to be able to make Remote Calls to Java Methods and display the result in Flex.

Today, we are going to make those efforts valuable by seeing how a user-defined object can be passed between Java & Flex. We will create a Employee List in Java and show it in a DataGrid in Flex. As Simple as that. To start with, you must have all the environment setup as explained here.

RPC with User Defined Objects

To be able to do so, we must create classes in both ActionScript and Java and bind them together as shown below:

Employee.java

EmployeeJava

Employee.as

EmployeeAS

The Java and the ActionScript file have the same attributes and they map to each other using Flex Metadata: RemoteClass(alias=””) which maps the java object returned from server to ActionScript object which can be displayed. This metadata tag used in ActionScript Class (Employee.as) specifies the fully qualified name of the corresponding Java Class. We now create a Utility class for getting Employee details:

EmployeeUtils.java

EmployeeUtils

Here, we have hard-coded the Employees Data, but it is as easy to get these employees from a database by firing a query. We now make a RPC call from Flex to get this list so that we can display it in a DataGrid.

getAllEmployees

We create a RemoteObject in Flex and specify a destination “employee” which is present in a remoting-config.xml to specify the Java Class file to look for methods called (getAllEmployees) using this RemoteObject. Part of flex-config.xml which specifies this looks like:

remotingConfig 

We specify the result and fault handlers with the remote object, which are called when result or fault occurs. In the result handler function, we save the result in a ArrayCollection, which we bind with our DataGrid as shown below:

employeeDatagrid

We set the dataProvider property of our DataGrid component to __employeeList, which is a bindable ArrayCollection which contains the result data. The advantage of making the ArrayCollection as bindable is that any changes made to this ArrayCllection (due to any event) is reflected in our DataGrid automatically.

When we run this example, we get a DataGrid as shown below:

output

Again this is not a best-way to code your flex application. The intent was to show how user-defined objects can be passed between Java & Flex. In practice and in large scale application, we would use tested frameworks like Cairngorm or PureMVC.

Wishing you very Happy Coding with Flex :-)

No comments: