Integrating Flex with Java using BlazeDS – first steps

Adobe Flex has become a trend when it comes to view layer between developers, analyst, managers and especially users, and can integrate with virtually any language programming. In the layer of business have a good race between Java and .NET(ok ok Java takes advantage).
For the Flex can integrate seamlessly with Java, you need a gateway(a device that works in any layer of the ISO/OSI to win “differences” between networks, manipulating and converting data). that can convert the native data types of Flex to data types native to Java and vice versa using AMF protocol..
In the following link we have the data types of Flex and its counterpart in Java:
http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_4.html
The AMF(Action Message Format) is protocol with open specification, compact and tranvels in binary format, and the ActionScript 3.0, will be the AMF3 supported data type specific to AS3.
Today we have several implementations that support AMF3, we use BlazeDS as a gateway for communication in ActionScript 3 and Java.
The database named “contacts” will be used MySQL with the following structure:
[SQL]
CREATE TABLE `tabela` (
`id` int(11) NOT NULL,
`nome` varchar(30) default NULL,
`email` varchar(100) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
[/SQL]
As application server we use the JBoss Application Server and will use the Eclipse and Flex Builder for coding respectively (you can to use Eclipse for Flex and Java in same IDE).
BlazeDS comes by default witn Tomcat, but it is only container servlet. With JBoss can use later ejb3, JPA, Hibernate etc.
Download the latest version of BlazeDS this link
Having everything and properly configured, let’s enconding:

  • Create a new project type “Dynamic Web Project” and name it “Contacts”.
  • Select the “Target Runtime” as JBoss and “Configurations” with “Default Configuration for JBoss v4.2.
  • In “Projects Facets” does not need to change anything, just click next.
  • In “Web Module” does not need to change anything, click Finish.

Done that we can begin our coding, but we will insert into project the BlazeDS libraries, if you downloaded the bin BlazeDS, just unzip the “blazeds.war” with some winrar and copy the diretory “WEB-INF\lib” into our project in “WebContent\WEB-INF\lib”, so then d the same thing with the directory “WEB-INF\flex” and the file “WEB-INF\web.xml”.
Configure JBoss to start the eclipse project and add the “Contacts” to be publised automatically on start JBoss (if you have not configured yet, follow the steps in this link).
Now let’s test our BlazeDS is properly configured, simply open the browser and enter the following address:

http://localhost:8080/Contatos/messagebroker/amf

if you see a blank page, it means that BlazeDS is ready to be used 😀

Let our VO, create a package called “br.com.leonardofranca.vo” and create a class called “ContatosVO”, your code is as follow:
[JAVA]
package br.com.leonardofranca.vo;

public class ContatosVO
{
private int id;
private String nome;
private String email;

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public String getNome()
{
return nome;
}

public void setNome(String nome)
{
this.nome = nome;
}

public String getEmail()
{
return email;
}

public void setEmail(String email)
{
this.email = email;
}
}
[/JAVA]

Until now, no mystery, we have a simple object to be typed using Java. Let our main class that will do all the work.
[JAVA]
package br.com.leonardofranca;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import br.com.leonardofranca.vo.ContatosVO;

public class Contatos
{
Connection conn;
Statement stm;
ResultSet rs;

public Contatos()
{
try
{
Class.forName(“com.mysql.jdbc.Driver”);
conn = DriverManager.getConnection(“jdbc:mysql://localhost:3306/meubanco”,”root”,”minhasenha”);
stm = conn.createStatement();
}
catch (Exception e)
{
e.printStackTrace();
}
}

public List< ContatosVO > getData()
{
List< ContatosVO > list = new ArrayList< ContatosVO >();
try
{
rs = stm.executeQuery(“SELECT id, nome, email FROM tabela”);
while (rs.next())
{
ContatosVO contatosVO = new ContatosVO();
contatosVO.setId(rs.getInt(“id”));
contatosVO.setNome(rs.getString(“nome”));
contatosVO.setEmail(rs.getString(“email”));
list.add(contatosVO);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return list;
}

public Boolean insertData(ContatosVO contatosVO)
{
try
{
String sql = “INSERT INTO tabela (nome, email) VALUES(‘”+contatosVO.getNome()+”‘,'”+contatosVO.getEmail()+”‘)”;
if(stm.execute(sql))
{
return true;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return false;
}

public Boolean deleteData(ContatosVO contatosVO)
{
try
{
stm = conn.createStatement();
String sql = “DELETE FROM tabela WHERE id = ‘”+contatosVO.getId()+”‘”;
if(stm.execute(sql))
{
return true;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return false;
}

public Boolean updateData(ContatosVO contatosVO)
{
try
{
stm = conn.createStatement();
String sql = “UPDATE tabela SET nome = ‘”+contatosVO.getNome()+”‘, email = ‘”+contatosVO.getEmail()+”‘ WHERE id = ‘”+contatosVO.getId()+”‘”;
if(stm.execute(sql))
{
return true;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return false;
}
}
[/JAVA]

In the constructr instantiate the class from the database, the following method is to list the data from the database, returning a List of Java that fed my DataGrid in Flex, the rest of the methods (insertm update and delete) just let me return a Boolean.

Now let the party in Flex.
We begin by VO part of Flex, note that it is necessary to put the “RemoteClass”:
[ACTIONSCRIPT3]
package br.com.leonardofranca.vo
{
[Bindable]
[RemoteClass(alias=”br.com.leonardofranca.vo.ContatosVO”)]
public class ContatosVO
{
public var id:uint;
public var nome:String;
public var email:String;

public function ContatosVO()
{
}

}
}
[/ACTIONSCRIPT3]
We now implement our presentation layer, we need a form with two fields name and emai, and a DataGrid to list the email database, we still nedd three buttons, one for insert, update and delete records from database.
[MXML]































[/MXML]
Usually now we would need to configure the services-config.xml for the swf know where to get the service. But do differently, i will set right in the endpoint of RemoteObject:
[MXML]






[/MXML]
And the tag method,mlet configured to call the methods in my Java class, Now just write the functions that will receive the returns of success or failure, note that i left the same method in case of failure.
[ACTIONSCRIPT3]
import mx.controls.Alert;
import mx.events.ListEvent;
import br.com.leonardofranca.vo.ContatosVO;
import mx.collections.ArrayCollection;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;

public function init():void
{
dg.addEventListener(ListEvent.CHANGE,selectedItems);
}

public function onResult(re:ResultEvent):void
{
var data:Object = re.message.body;
dg.dataProvider = data;
}

public function onFault(fault:FaultEvent):void
{
trace(“Code: “+fault.fault.faultCode);
trace(“Detail: “+fault.fault.faultDetail);
trace(“String: “+fault.fault.faultString);
}

public function insertData():void
{
var contatosVO:ContatosVO = new ContatosVO();
contatosVO.nome = input_nome.text;
contatosVO.email = input_email.text;
ro.insertData(contatosVO);
}

public function onResultData(re:ResultEvent):void
{
ro.getData();
}

public function deleteData():void
{
if(dg.selectedItem != null)
{
var contatosVO:ContatosVO = new ContatosVO();
contatosVO.id = dg.selectedItem.id;
ro.deleteData(contatosVO);
}
else
{
Alert.show(“Selecione um item da tabela!!!”);
}
}

public function selectedItems(evt:ListEvent):void
{
input_nome.text = dg.selectedItem.nome;
input_email.text = dg.selectedItem.email;
}

public function updateData():void
{
if(dg.selectedItem != null)
{
var contatosVO:ContatosVO = new ContatosVO();
contatosVO.id = dg.selectedItem.id;
contatosVO.nome = input_nome.text;
contatosVO.email = input_email.text;
ro.updateData(contatosVO);
}
else
{
Alert.show(“Selecione um item da tabela!!!”);
}
}
[/ACTIONSCRIPT3]
Following the complete code:
[MXML]


< mx : Script>
< ![CDATA[ import mx.controls.Alert; import mx.events.ListEvent; import br.com.leonardofranca.vo.ContatosVO; import mx.collections.ArrayCollection; import mx.rpc.events.FaultEvent; import mx.utils.ObjectUtil; import mx.rpc.events.ResultEvent; public function init():void { dg.addEventListener(ListEvent.CHANGE,selectedItems); } public function onResult(re:ResultEvent):void { var data:Object = re.message.body; dg.dataProvider = data; } public function onFault(fault:FaultEvent):void { trace("Code: "+fault.fault.faultCode); trace("Detail: "+fault.fault.faultDetail); trace("String: "+fault.fault.faultString); } public function insertData():void { var contatosVO:ContatosVO = new ContatosVO(); contatosVO.nome = input_nome.text; contatosVO.email = input_email.text; ro.insertData(contatosVO); } public function onResultData(re:ResultEvent):void { ro.getData(); } public function deleteData():void { if(dg.selectedItem != null) { var contatosVO:ContatosVO = new ContatosVO(); contatosVO.id = dg.selectedItem.id; ro.deleteData(contatosVO); } else { Alert.show("Selecione um item da tabela!!!"); } } public function selectedItems(evt:ListEvent):void { input_nome.text = dg.selectedItem.nome; input_email.text = dg.selectedItem.email; } public function updateData():void { if(dg.selectedItem != null) { var contatosVO:ContatosVO = new ContatosVO(); contatosVO.id = dg.selectedItem.id; contatosVO.nome = input_nome.text; contatosVO.email = input_email.text; ro.updateData(contatosVO); } else { Alert.show("Selecione um item da tabela!!!"); } } ]]>


< mx : method name="getData" result="onResult(event);" fault="onFault(event);"/>

































[/MXML]
If you got this far ok! everything right and working, but you can forget, i will go show a better and efficient to integrate Flex with Java 😉

[UPDATE]
I forgot to mention that you need a directory of the project in eclipses, called “WebContent/WEB-INF/flex” to be included in the files: services-config.xml, remoting-config.xml, proxy-config.xml, messaging-config. xml. the project is only necessary that the remoting-config.xml, whose content should be like the code below
[XML]





br.com.leonardofranca.Contatos
session


[/XML]

Recommended books:

Translations:
Português do Brasil

Was this article helpful? feel free to make a donation and help keep the blog in the air
BlazeDS, Flex, Java, MySQL , , ,

11 comments


  1. Pingback: Leonardo França » Integrando Flex com Java usando BlazeDS – primeiros passos

  2. Pingback: Leonardo França » Adobe Flex with PHP using ZendAMF – first steps

Leave a Reply