Nitin has posted 391 posts at DZone. View Full User Profile

Flex on Grails

  • submit to reddit

In this article, excerpted from "Flex on Java," (Manning, Sept 2010) authors Bernerd Allmon and Jeremy Anderson show you how to rapidly prototype data-enabled Flex applications using Groovy and Grails in combination with the Flex plugin for Grails. The article starts by defining the domain in Grails and exposing some services for your Flex application to use, and the Flex application itself. It then goes one step further and shows you how to enable your application to use JMS and ActiveMQ for real-time updating of your UI. 


By Bernerd Allmon and Jeremy Anderson

Not all real-world development is against an existing application. Every once in a while you have fun developing new code. What do you do when you want to rapidly prototype a data-driven application with Flex? With the Flex part it’s easy enough to develop a UI, but what about the backend? You could always develop a Java-based backend using the same methods and techniques we described throughout this book or you could take advantage of another framework, such as Grails XE "Grails" , to quickly get your data-driven backend off the ground.

Get a 40% discount on this book!
Click here to purchase it directly from Manning and use code "dzone40". 


Why Groovy and Grails?

Groovy XE "Groovy:much like Java 2.0"  has been affectionately called Java 2.0 XE "Java 2.0"  by many in the Java world, so it should be no surprise that you can integrate with Groovy and Grails as easily—and in some aspects more easily—as in previous chapters.

You may be wondering “Why Flex and Grails?” To which we respond, “Why not?” In this article we’re going to demonstrate how you can quickly build and prototype data-enabled Flex applications, leveraging the rapid development provided by Groovy and Grails coupled with the powerful Grails plugin for Flex. Whether your intent is to spike out a particular piece of functionality or to build a complete application, there are few options that will allow you to develop as rapidly as Grails.

Groovy is Java 2.0


We’re going to assume that you are at least somewhat familiar with both Groovy and Grails, but if you’ve never seen or done any development using either, you should still be able to follow along. We’ll show idiomatic Groovy code but won’t go into too much detail about what the code does as that is beyond the scope of this article. If you want to learn more about Groovy we suggest starting with the Groovy homepage or by reading book Groovy in Action, Second Edition by Dierk Koenig, published by Manning Publications. In this article we’ll be building a simplified contact management application called Flex Contacts. You’ll build a single Master-Detail XE "Master-Detail"  screen that you can use to track your contacts as shown in figure 11.1.

Figure 11.1 The sample application

Before you start writing the application, you’ll need to install Grails.


Downloading and installing Grails

Installing Grails XE "Grails:installing"  is a rather simple task. Point your browser to the Grails project downloads page and download the appropriate distribution for your platform. This article was written using Grails 1.1.2, which was the latest stable distribution available at the time of writing. There is no reason to install Groovy separately because it’s included with the Grails distribution. Grails is available in two main forms, a binary distribution and a source distribution. Download the binary distribution in either Zip or Tar/GZ format, depending on your operating system.

After you’ve downloaded the binary distribution for Grails, unzip the Grails distribution to a folder such as c:\dev\grails-1.1.2. Then create a GRAILS_HOME environment variable and point it to the same folder. As a last step, append GRAILS_HOME\bin to your PATH variable so that you can run the Grails executable from the command line. When you’ve finished, open up a command line and type grails –version and you should see output similar to this snippet.

C:\dev> grails -version

Welcome to Grails 1.1.2 -
Licensed under Apache Standard License 2.0
Grails home is set to: C:\dev\grails-1.1.2

Base Directory: C:\dev


Congratulations! You’ve got Grails installed and configured. Now let’s move on to creating the Grails application.


Creating the Grails application

Here’s where you see one of the first examples of Grails’ convention over configuration XE "Grails:convention over configuration"  XE "convention over configuration"  way of doing things. To create your Grails application, you must open a command line and navigate to the folder where you want to create your Grails application, for example c:\dev\projects\ and type the following command.

C:\dev\projects\> grails create-app flex-contacts


With that one simple command Grails has enough information to generate your project for you. No hard to remember or cryptic command line parameters, one simple concise command and Grails creates the project structure and installs all the necessary dependencies. You don’t even have to install a database server or servlet container to run the application; that’s all included out of the box when you create your Grails application. If you think that was easy, wait until you see how easily you can add functionality to your Grails application using plugins XE "Grails:plugins" . But first, let’s continue building the Grails application by starting with defining the domain model.


Create the Contact domain model

Next you’ll create the domain class that will be responsible for holding contact information. For this you’ll need only one domain object called Contact. Create the Contact object by issuing the following command:

C:\dev\projects\flex-contacts\> grails create-domain-class contact


This will create the Contact domain model class in the grails-app/domain folder within your flex-contacts project. In the Contact domain model, you’re going to add a few simple properties for persisting the contact information such as first name, last name, and address information, as well as simple validation constraints. Here is what your completed Contact.groovy file will look like.


Contact.groovy file

class Contact {

static contstraints = { #1
firstName(blank: false, minLength: 4, maxLength: 15)
lastName(blank: false, minLength: 4, maxLength: 25)
state(blank: false, length: 2)
zipCode(blank: false, minLength: 5, maxLength: 10)
} #1

String firstName #2
String lastName
String address
String city
String state
String zipCode #2

String toString() { #3
return firstName + " " + lastName

#1 Constraints
#2 Properties
#3 toString()

The Contact class contains fields that you’ll need to hold things like first name, last name, and address (#2). You’ve also defined a few constraints (#1) so that you can validate that you get all the information you need from the frontend. You’ve also implemented a toString() (#3) method to provide a more meaningful implementation than the default. Now let’s create the service that you’ll be exposing to the Flex application.


Create the ContactService

To expose your Grails application to the Flex frontend, create a service that will expose the functionality for your application to perform CRUD operations on your Contact domain object. To do this you issue the following command on the command line:

C:\dev\projects\flex-contacts> grails create-service contact


This will create a class named ContactService, shown in listing 11.2, in the grails-app/services folder. The ContactService will contain the methods you’ll be exposing to Flex to consume as a remote service. Inside the ContactService.groovy file you’ll implement a few simple methods to enable your Flex application to get a list of all the contacts in the database, get a specific contact, save a contact, and delete a contact from the database.

ContactService.groovy file

class ContactService {

static expose = ['flex-remoting'] #1

boolean transactional = true #2

def getContacts() { #3
return Contact.list()

def get(id) { #3
return Contact.get(id)

def update(Contact contact) { #3

def remove(Contact contact) { #3

contact.delete(flush: true)



#1 Expose to Flex
#2 Transactional property
#3 Service methods

Most of the ContactService class should look familiar to you. The only line that may look odd is the one that contains the code static expose = ['flex-remoting'] (#1). This single line of code is all you need to expose this service XE "Grails:expose service"  to Flex so that you can call any of the service methods from your Flex application. You also make all of the service methods (#3) in your service transactional by setting the transactional property to true (#2). The Flex plugin for Grails, which we’ll install in a bit, follows the Grails philosophy of convention over configuration in that it abstracts much of the configuration that you would have needed to build had this been a Java application leveraging either BlazeDS or LiveCycle Data Services to expose this functionality.


Bootstrap sample data

The last step building the Flex client is to bootstrap your application with sample data so that you have contact information in the database when you first run it. This will also allow you to see that the Flex remoting is working correctly. To do this you add the code shown next to the BootStrap.groovy XE "BootStrap.groovy"  file in the grails-app/conf folder of your application.

BootStrap.groovy file

class BootStrap {

def init = {servletContext ->

Contact contact1 = new Contact(firstName: "Jeremy", #1
lastName: "Anderson", address: "123 Main St",
city: "Jenison", state: "MI", zipCode: "49428")

Contact contact2 = new Contact(firstName: "BJ", #1
lastName: "Allmon", address: "234 Any St",
city: "Delaware", state: "OH", zipCode: "43015")

def destroy = {

#1 Sample data

Bootstrapping data in Grails allows you to have data injected into the application each time you restart it. You do this by creating a couple of Contact objects (#1) in your BootStrap.groovy file and call save() on them to persist them to the database. This is a helpful feature of Grails as you move through development and beats having to manually enter contacts every time. You would typically use this file for bootstrapping any kind of initial data in your application, such as states and state codes. Now you’re ready to begin developing the Flex frontend for the Grails application you created.


Getting rich with Flex

Now that you have created your Grails application you can move on to the task of creating the Flex client that will integrate with Grails. You’ll start by installing the Flex plugin XE "Grails:install Flex plugin"  for Grails, and then you’ll add the Flex application to the Grails project.


Installing the Flex plugin

From the root of the project directory enter the following command to install the Flex plugin for the Grails application:

C:\dev\projects\flex-contacts\> grails install-plugin flex


This command will pull down all of the Flex libraries your application needs to be able to compile the Flex application. This may take time because the plugin has to pull down many dependencies. After all the messages have scrolled by, the plugin should be successfully installed. Like many other features in Grails development, enabling an application for Flex integration is extremely simple and declarative. No configuration files need to be created, though some configuration files are contained within the web-app/WEB-INF folder if you need to fine-tune the Flex compiler settings.


Creating the domain classes in Flex

You can begin the Flex development by creating a domain object in ActionScript. This object will act as a data transfer object of sorts, allowing you to deal with full-fledged objects when your service returns data to the client. This approach avoids having to deal with the pseudoproxy objects that Flex would wrap your objects into if it didn’t have anything to translate it into.

When you installed the Flex plugin in the previous step, it created a flex folder under web-app/WEB-INF. Inside this folder resides another folder called user-classes, which contains a file that clues you into where you’re supposed to place your ActionScript classes, appropriately called add_your_as_and_swc_files_here. Create a file in the user-classes folder called

package {

[Bindable] #1
[RemoteClass(alias = "Contact")] #2
public class Contact {

public function Contact() {

public var id:*; #3
public var version:*; #3

public var firstName:String #4
public var lastName:String
public var address:String
public var city:String
public var state:String
public var zipCode:String #4


#1 Bindable
#2 RemoteClass
#3 Hibernate specific properties
#4 Public properties


The code should resemble the client side domain classes that you created earlier for your FlexBugs application. Take note of the annotations at the top of the file, [Bindable] (#1) and [RemoteClass] XE "[RemoteClass]"  (#2). The [Bindable] XE "[Bindable]"  XE "annotation:[Bindable]"  annotation lets Flex know that whenever one of the values changes in this object, it should notify anything else that is bound to this object to let it know that it should update itself. We didn’t utilize data binding in our other application but for this quick example we did, in order to keep the examples shorter.

In case you have forgotten, the [RemoteClass] XE "annotation:[RemoteClass]"  XE "[RemoteClass]"  annotation allows a Flex class to be mapped to a server-side class. The class is mapped to the Contact.groovy domain class you created earlier. Because you’re using a package structure in this trivial example, you don’t need to fully qualify it here; if your domain object in Grails fell under a specific package, you would have to fully qualify that object in this annotation for it to work correctly.

You need to add a couple of Hibernate XE "Hibernate" -specific properties (#3) to your Contact domain class for your application to behave as intended, along with all the normal public properties (#4) that you need to include for the data fields you want to be able to be persist.


Creating the Flex application

Now that you’ve got your domain object created for the client side, you’ll need to create a file to contain the main Flex application itself, which will be called main.mxml and is created in the web-app folder of your Grails application.

You’ll break this down into bite-sized chunks that should be easier to digest than if you were simply presented with the end state of the application. First you’ll start by creating the Application XE "Application"  object. As in the other sample application, your Flex application will have the Application element as its root node of the MXML file as shown in this snippet.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx=""


Now that you’ve got the base application started, you’re ready to start laying out the basic layout.


Defining the layout

Look at figure 11.1 again, and take note that you’ve got three main containers in use for this application. You’ve got the header at the top containing the text Flex Contacts on Grails, and two panels containing the master view and the details view. Let’s create the basic layout for your application. To do that you’re going to leverage a couple of layout components XE "layout components" : HBox and Panel.  We'll break up the Main.mxml and look at each section individually.

Main.mxml (a)

<mx:HBox width="100%">                                                 #1
<mx:Text fontSize="24" text="Flex Contacts on Grails"/>
<mx:HBox width="100%" height="100%">
<mx:Panel width="65%" title="Contacts" height="100%"> #2

<mx:Panel width="35%" title="Edit Contact" height="100%"> #3


#1 Header container
#2 Master view
#3 Detail view


This listing shows the code used to generate the layout of our application. In the snippet we saw previously, you specified that your Application use vertical as its main layout method so your components will flow vertically down as you add them to the application. Here you start by adding an HBox container (#1) containing a single Text component. This Text component contains the text for our title that appears in the header. Next you wrap two Panel containers in another HBox so they’ll show up side by side in the application. These two Panel components will house the master view (#2) and detail view (#3).


Creating the master view

Inside the first Panel container you’ll create the master view using the DataGrid component, which allows you to display tabular data rather painlessly.

Main.mxml (b)

<mx:DataGrid id="contactsGrid"
dataProvider="{contactsList}" #1

<mx:DataGridColumn dataField="id" headerText="ID" width="50"/> #2
<mx:DataGridColumn dataField="firstName"
headerText="First Name" width="100"/>
<mx:DataGridColumn dataField="lastName"
headerText="Last Name" width="100"/>
<mx:DataGridColumn dataField="address" headerText="Address"/>
<mx:DataGridColumn dataField="city" headerText="City" width="120"/>
<mx:DataGridColumn dataField="state" headerText="State" width="70"/>
<mx:DataGridColumn dataField="zipCode" headerText="ZipCode"
width="100"/> #2

<mx:ControlBar> #3
<mx:Button label="Delete Contact"
enabled="{contactsGrid.selectedItem != null}"
<mx:Button label="Refresh" click="contactService.getContacts()"/>
</mx:ControlBar> #3

#1 DataProvider
#2 DataGrid columns
#3 ControlBar


This portion of the listing shows the code to create the contacts DataGrid XE "DataGrid"  as well as to define the columns to be displayed. You may have noticed the items contained within the curly braces {}; this is how to specify data binding XE "Flex:specifying data binding"  XE "data binding:in Flex"  in a Flex application. You’ve bound the dataProvider property (#1) of the DataGrid to the contactsList variable, which you’ll define later. This is where you’ll store the results from your RemoteObject XE "RemoteObject"  method call to get all the contacts. Notice that all of your column names (#2) should match what you defined in the Contact object you created earlier. This allows Flex to automatically figure out which data field to map to which column.

A ControlBar XE "ControlBar" (#3) will contain all of the buttons needed to interact with this control.

image003.gif13.43 KB
image002.jpg19.65 KB
Published at DZone with permission of its author, Nitin Bharti.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)


Sebastien Arbogast replied on Tue, 2010/08/24 - 12:48pm

Too bad this article uses a technique that is at best very unlikely to be used in a real-world context, mainly for 3 reasons:

  1. The Flex plugin has not been maintained for years, and it uses the old-fashioned way of integrating BlazeDS into Spring instead of the more modern, robust and easy to configure Spring BlazeDS integration library
  2. It doesn't talk at all about authentication and authorization which is for me a critical issue in any remoting setup. And the Flex plugin doesn't really offer a solution to that.
  3. The Flex plugin integrates BlazeDS3 and suggests you should mix your Flex sources with Grails project, which doesn't make it easy to work on the Flex part using Flash Builder and its great data connectivity wizards.

Those are the 3 reasons why I've been working on the Grails BlazeDS plugin ( which works great with Grails up to version 1.2.x. Unfortunately I'm tackling some challenges with Grails 1.3 and even if I get things working, there are still some limitations with Flash Builder.

So from a Grails/Flex integration standpoint, we end up being stuck between an old solution that is working but incomplete and not integrated in tools, and a more modern solution that does not work anymore and forces us to use some workarounds.

All the community needs to make this work is a little coordinated help from Adobe and SpringSource so that we can have:

  • a BlazeDS 4 + Spring BlazeDS 1.5 + Spring Security 3 integration plugin for Grails 1.3 and above
  • a data connectivity wizard that does not require a standard WAR layout and is capable of generating client stubs based on Groovy classes.


I've left a couple of messages on Grails mailing lists ( and, Adobe forums ( and SpringSource forums (, but so far, all my calls for help have remained unanswered. So if anyone is willing to help or support this ongoing initiative, it'll be greatly appreciated.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.