Building Flex and Java based CRUD application using Flash Builder 4

Updated for Flash Builder 4 release version🙂

In this article we will create a CRUD application using Adobe Flex and Java. Flash Builder 4 allows you to build Flex front end for Java classes on the server with just couple of clicks, so we will use Flash Builder 4 to develop the application.

BlazeDS is a Java based server technology from Adobe which lets you invoke methods in Java class on server from your Flex applications. BlazeDS is the best solution for integrating Flex with Java so obviously we will use this in our sample project.

Below are the steps we will follow to complete our application

  1. Set up BlazeDS (copying files :))
  2. Expose Java class as Remoting service destination
  3. Use Flash Builder to generate Flex code to invoke methods in Java class on the server
  4. Retrieve data from server and display in the application
  5. Allow user to add/update/delete entries in a database table from the application

Article allows you to skip any of steps mentioned above and copy the code🙂 Let’s get started🙂

You can download the completed project from here http://sujitreddyg.com/fb4articles/release/BlazeDSCRUD.fxp

Set up BlazeDS

Download BlazeDS binary distribution from this URL Download (4MB) and follow instructions at this URL to setup BlazeDS https://sujitreddyg.wordpress.com/2009/04/07/setting-up-blazeds/

Once BlazeDS is setup you need to expose the Java class as Remoting destination, visit this URL to know how to expose a Java class as Remoting destination https://sujitreddyg.wordpress.com/2008/01/14/invoking-java-methods-from-adobe-flex/

After exposing your Java class as Remoting destination using BlazeDS, follow steps below to build the Flex application.

In this sample we will expose SimpleCustomerService.Java as Remoting destination. SimpleCustomerService communicates with database and returns SimpleCustomer objects.

Setting up BlazeDS RDSDispatchServlet

After setting up BlazeDS, you have to enable RDSDisptachServlet, which is used by Flash Builder 4 to get destination details. This is disabled by default. It’s very simple all you have to do is to un-comment/add the Servlet mapping in the web.xml.

Copy the Servlet URL mapping and declaration for the RDSDispatchServlet below and copy it into your web application web.xml under <web-app> node.

<servlet>
<servlet-name>RDSDispatchServlet</servlet-name>
<display-name>RDSDispatchServlet</display-name>
<servlet-class>flex.rds.server.servlet.FrontEndServlet</servlet-class>
<init-param>
<param-name>useAppserverSecurity</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>10</load-on-startup>
</servlet>
<servlet-mapping id=”RDS_DISPATCH_MAPPING”>
<servlet-name>RDSDispatchServlet</servlet-name>
<url-pattern>/CFIDE/main/ide.cfm</url-pattern>
</servlet-mapping>

Install Flash Builder 4

Download and install Flash Builder 4 from this URL http://www.adobe.com/products/flashbuilder/

Creating new Flex project with BlazeDS server configurations

Create new Flex project

Create a new Flex project from File -> New -> Flex Project and enter project details as shown below.

In this screen:

  1. Enter project name
  2. set “Web (runs in Adobe Flash Player)” as the application type
  3. Use default Flex SDK (Flex 4.0)
  4. Set the application server type to J2EE
  5. Select BlazeDS
  6. Click on Next to continue

Configure J2EE server settings


In this screen:

  1. Set the Root folder to the root folder of your web application with BlazeDS configured. Its C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\demo in this sample
  2. Set the Root URL to root URL of your BlazeDS enabled web application
  3. Set the Context root to context root of your BlazeDS enabled web application
  4. Leave the output folder to default value
  5. Click on validate configuration button
  6. Click finish to continue

Using DCD feature to connect to consume Remoting Service

DCD or Data-Centric Development is one of the advancements to the Flash Builder 4 which lets you develop data centric applications very easily. In this sample we will see how to create a Flex application which consumes BlazeDS Remoting service. Same steps can be followed for LCDS Remoting services also.

Creating Service using DCD


  1. Select the Data/Services window shown in the image above. If this is not visible, select it from Window -> Data/Services
  2. Click on “Connect to Data/Service” (highlighted in the image) in the Data/Services window
  3. Window as shown in the image below will be launched

Select BlazeDS and click on Next. Flash Builder will display a window asking for RDS credentials. Since we turned off security for our RDSServlet by setting the “useAppserverSecutiry” parameter to “false” in the web.xml, select “No password required” and click on OK to continue.

Selecting Remoting destination

You can see that Flash Builder listed all service destinations exposed from your web application as shown in the screen below.

In this screen we are selecting the destination the newly created service should use. Select a destination (SimpleCustomerServiceDestination in this sample) and click on Finish to continue.

Code for invoking the Remoting service will be generated, you can see the service and its operations (methods exposed by the Java class) being displayed in the “Data/Services” window and in the package explorer.

Flash Builder 4 introspects return types for the Java class methods and creates AS3 classes for any custom Java classes.  We have the service class ready, let’s create UI.

Creating UI

Please copy the code from this URL http://sujitreddyg.com/fb4articles/release/BlazeDSCRUD_1.mxml.txt into your main application file (BlazeDSCRUD.mxml in this sample). Code in the URL will add UI controls required for this sample application. After copying the code, your Flash Builder design view should look as shown in the image below.

Note: In this article to refer to a control, we will use value set for the id property of the controls.

Create Form for the Customer data type

We will display the details of the customer entry selected in the listCustomers control (created in previous step) in formSelectedCustomer. Using Flash Builder you can bind a Form control to an entity instance.  Right click on the formSelectedCustomer and select “Bind to Data” as shown in the image below.

Flash Builder will display window as shown in the image below.

In this screen:

  1. We want the Form items to be generated based on a data type (SimpleCustomer) so select “Data type”
  2. Select SimpleCustomer from the list of data types
  3. We want the form to be editable, so select the “Make form editable” check box
  4. Click Next to continue
  5. Flash Builder will display the list of properties in the selected data type as shown in the image below. Flash Builder will also assign a UI control which it will use to display the property value as shown in the image below.

In this window, you can select the items which you want to be included in the form and UI control in which you want the property value to be displayed. You can also arrange the controls in the order in which you want them to be displayed. Arrange the properties and modify the controls as shown in the image above.

Flash Builder will add FormItems to formSelectedCustomer and binds the values of the controls under formSelectedCustomer to SimpleCustomer instance. In this sample Flash Builder generated a SimpleCustomer instance with “simpleCustomer” as its id. So we will refer to the SimpleCustomer instance bound to the items in formSelectedCustomer as simpleCustomer.

Binding data to UI Controls

Now that we have our UI ready, let’s get the data from the server and display it in the application.

Right click on the List and click on “Bind to Data ..” as shown in the image below.

Flash Builder will display window as shown in the image below.

In this screen:

  1. Select New service call
  2. Set Service to SimpleCustomerServiceDestination
  3. Set Operation to getAllCustomers(): SimpleCustomer[]
  4. Set Bing to field to customerName
  5. Click on OK to continue

In previous step we bound the service call result to listCustomers component, listCustomers will send a request to the getAllCustomers() function on the server and displays the result.

listCustomers is displaying only the name of the customer, so let’s display complete details of the  customer in formSelectedCustomer. Right click on the listCustomers and select “Generate Change Handler” as shown in the image below.

Flash Builder will generate a function which will be invoked when user selects a different item in the listCustomers. Flash Builder will also switch the view to Source view as shown in the image below, so that you can write code in the handler function generated.

Add the code below to the generated change handler function as shown in the image above.

simpleCustomer = listCustomers.selectedItem as SimpleCustomer;

In the code snippet above, simpleCustomer is the instance of SimpleCustomer which was bound to the formSelectedCustomer. In the code above, we are passing the reference of the selected SimpleCustomer instance in listCustomers to the SimpleCustomer instance bound to formSelectedCustomer. This line of code will populate formSelectedCustomer with details of the selected customer in listCustomers control.

Now, let’s keep formSelectedCustomer populated with values of the first customer entry in listCustomers as soon as the customer data is loaded from the server.

Understanding the CallResponder

How will you know when the data is returned from the server? For each service call generated in the application there will be a CallResponder class instance associated with it. CallResponder dispatches result event when the call to the service is successful and the data returned from the server can be accessed using a property called lastResult in CallResponder instance. To map the CallResponder instance with the service call, you have to pass the reference of the AsyncToken returned by the service call to the token property of the CallResponder.  You can see service call AsyncToken reference passed to the CallResponder in listCustomers_creationCompleteHandler function as shown below.

protected function listCustomers_creationCompleteHandler(event:FlexEvent):void

{

getAllCustomersResult.token = simpleCustomerServiceDestination.getAllCustomers();

}

CallResponder class will dispatch result event when the data is retrieved successfully from the server. You can add a handler to the result event to perform any logic when the server response is successful. In our case we will keep the first Customer in the listCustomers to be selected and its value to be displayed in formSelectedCustomer as soon as the data from the server is loaded on to the client.

Add a result event handler to the getAllCustomersResult CallResponder as shown in the image below.

In the generated result handler add the following code. In the code below list is the List instance added in previous steps.

if(listCustomers != null)

{

listCustomers.selectedIndex = 0;

simpleCustomer = listCustomers.selectedItem as SimpleCustomer;

}

You can observe that Flash Builder also generated a Button (id=”button”) and also generated a click handler (button_clickHandler) for the Button, in which code to bind the values in the Form (id=”formSelectedCustomer”) to simpleCustomer object. Just delete the Button and the click handler.

You can see the BlazeDSCRUD.mxml file with code till this step at this URL http://sujitreddyg.com/fb4articles/release/BlazeDSCRUD_2.mxml.txt

At this point you can save and run the application. Application will launch in a browser and displays the data retrieved from the server as shown in the image below. You can view details of the customs by selecting them from the list.

Performing Add/Update/Delete operations

In the SimpleCustomerService Java class on the server we have methods which can perform Add/Update/Delete operations in the database. If you observe Flash Builder generated AS3 functions in SimpleCustomerServiceDestination.as class for each public method of the selected Remoting destination including the addCustomer() , updateCustomer() and deleteCustomer(). We just have to invoke these AS3 function in order to invoke corresponding Java method on the server.

Let’s invoke functions in the SimpleCustomerDestination AS3 class when user clicks on Add/Update/Delete buttons created earlier.

Right click on the button labeled “Add” (id = “btnAdd”) and select “Generate Service Call ..” as shown in the image below.

Flash Builder displays window as shown in the image below, in which you can select the service call which you want to invoke when user clicks on the Button.

In this screen:

  1. Set the Service to SimpleCustomerServiceDestination
  2. Set the Operation to addCustomer(arg0:SimpleCustomer)
  3. Click on OK to continue

The addCustomer function selected expects an argument of the type SimpleCustomer . So Flash Builder 4 will switch to the source view and lets you enter the argument as shown in the image below.

Let’s pass the changes made in the Form (id=”formSelectedCustomer”) to the simpleCustomer instance and then pass simpleCustomer as an argument to the addCustomer function as shown in the image above. Code in the button click handler function will look as shown below. In the code snippet below we are passing the AsyncToken returned by addCustomer function to addCustomerResult, so that addCustomerResult object will dispatch result event when the service call is successful.

protected function btnAdd_clickHandler(event:MouseEvent):void

{
simpleCustomer.customerName = customerNameTextInput.text;
simpleCustomer.customerType = customerTypeTextInput.text;
simpleCustomer.customerAddress = customerAddressTextInput.text;
addCustomerResult.token = simpleCustomerServiceDestination.addCustomer(simpleCustomer);

}

Similarly generate service calls for Update and Delete buttons, select updateCustomer and deleteCustomer operations respectively and pass the same simpleCustomer object with modified values as argument. After generating service calls for other two buttons your application code in this URL http://sujitreddyg.com/fb4articles/release/BlazeDSCRUD_3.mxml.txt

Clicking on the Add/Update/Delete buttons will reflect the changes on the server. Let’s get the updated collection of customers from the server by invoking getAllCustomers function of the SimpleCustomerServiceDestination class if the Add/Update/Delete operations are successful.

You will have CallResponder instances created for Add, Update and Delete service calls in the application, invoke getAllCustomers() function in the result event of these call responders so that we will get updated customers list after Add, Update and Delete operation are performed successfully.

You can view/copy the completed BlazeDSCRUD.mxml file at this URL http://sujitreddyg.com/fb4articles/release/BlazeDSCRUD.mxml.txt

Save and run your application. You will see your application launched in a browser and ready for performing CRUD operations on the database entries.

Data centric applications can be developed very easily and effectively using Data Centric Development features in Flash Builder 4. Try enabling client side data management and client side data paging for the service used in this article, you can find the articles at the URL below. Please find more articles on using features in Flash Builder 4 at this URL https://sujitreddyg.wordpress.com/flash-builder-4/

Adobe Rocks🙂

21 Responses to Building Flex and Java based CRUD application using Flash Builder 4

  1. wzinc says:

    Is

    RDSDispatchServlet
    /CFIDE/main/ide.cfm

    intended for coldfusion while we are talking about java?

  2. Hi Wzinc,

    This is just a URL mapping and the servlet mapping in this article is for J2EE projects only🙂 If you observe we are mapping /CFIDE/main/ide.cfm URL to flex.rds.server.servlet.FrontEndServlet which is a Java class🙂

    Point is Flash Builder will send request to this URL /CFIDE/main/ide.cfm irrespective of whether the project is based on CF/BlazeDS/LCDS. If the back-end is CF respective CFM file will be invoked. If the back-end is BlazeDS/LCDS because of the URL mapping in web.xml the FrontEndServlet will be invoked.

    Hope this helps🙂

  3. Duane says:

    great examples!

    After I add a record how do I reset the simpleCustomer object so I can add another record?

    Thanks,

  4. Hi Duane,

    You can try

    simpleCustomer = new SimpleCustomer()

    Hope this helps.

  5. handoyo says:

    Hi Sujit,i wonder if is it possible to use jasper report within the application?Thanks…

  6. David Pronk says:

    Hi Sujit,

    The download at http://flexorg.wip3.adobe.com/blazeds/trunk/11835/blazeds-bin-4.0.0.11835.zip no longer exists. You might want to update this url.

  7. Hi David,

    Thank you very much. Updating the URL🙂

  8. kristine says:

    hi Sujit,
    i am working with blazeds,hibernate and eclipse ganymede. right now i am having problem with jasper report integration to my technology. can you please help me resolve this problem? thanks.

  9. Domnic says:

    Hi Sujit,
    Thanks for your excellent posts here. I would like to know bit more about the CallResponder. So far I didnt come across docs where data binding is made for NON-UI elements like ArrayList. Here you are getting the SimpleCustomer objects using getAllCustomersResult.token = simpleCustomerServiceDestination.getAllCustomers(); and the objects are available in the getAllCustomersResult.lastResult, now how can I know the size of this object array ? say I want to retrieve the data from all these objects for a particular column customerName. Any code example or a API explanation would be highly appreciated.

  10. Pepe says:

    Hi Sujit,

    How i can show alert with return createdCustomerId

    Thank !!

  11. Pepe says:

    Hi,

    I do it.

  12. kalai says:

    Hi Sujith,

    I could manage building a simple dashboard after having read through all your posts. Below is the URL for your reference.
    http://www.tawn.tnau.ac.in/Dashboard.html

    Thank you so much!

  13. Stefan says:

    Hello,

    Flex-BlazeDS-Java works fine for me when using BlazeMonster, but when I try to use DCD I get the following error:


    Caused by: java.lang.RuntimeException: RDS server message:
    Could not initialize class com.adobe.rds.core.services.Messages
    at com.adobe.flexbuilder.services.j2eeservice.J2EEServicePage.initialize(J2EEServicePage.java:187)

    Any ideas what I’m missing here?

    Regards,
    Stefan

  14. Ron says:

    The link to download the projrct seems to be broken

  15. Hi Ron,

    Can you please let me know which link is broken.

    Thank you🙂

  16. Hi Stefan,

    Can you please share the complete stack trace.

  17. asha says:

    Hi Sujit,

    java.lang.ClassNotFoundException:
    flex.rds.server.servlet.FrontEndServlet

    Am getting the above string in console when i run the flex prg as a web application.
    Actually my flex code is not hitting java code and retrieving the values frm java code. my config files r correct.
    Do u have a solution??

  18. asha says:

    Hi Sujit,

    The exception I told u above is cmng like this

    Feb 23, 2011 4:21:24 PM org.apache.catalina.core.StandardContext loadOnStartup
    SEVERE: Servlet /Final threw load() exception

    thank u.

  19. Elmore says:

    Hi Sujit,

    I’m a new comer to Flash Builder 4 and have been searching everywhere (including the adobe website) for examples of a basic CRUD app written for this platform but to no avail. Your articles are very neatly laid out and very easy to follow, I was up and running in a few hours considering I had no previous experience with BlazeDS integration. It’s all downhill from here for me.

    Thank you very much.

  20. Hi Asha,

    Can you please check if you have flex-rds-server.jar in your web application class path. If you are using earlier versions of BlazeDS please check this article https://sujitreddyg.wordpress.com/2009/06/01/using-flash-builder-4-for-earlier-blazeds-builds/

    Hope this helps.

  21. Hi Elmore,

    Thanks! Glad these posts helped🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: