Invoking JBoss Web Services with Flex

User Rating: 0 / 5

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive
 

Flex® is a free, open source framework for building highly interactive, expressive web applications that deploy consistently on all major browsers, desktops, and operating systems. It provides a modern, standards-based language and programming model that supports common design patterns. In this tutorial we'll explore how to connect to JBoss webservices using a Flex Interface.

 

As we said Flex uses a declarative XML-based language (MXML) to describe UI layout and behaviors. In addition, to create the client login, it can use ActionScript 3, a which is a powerful object-oriented programming language.

One of the benefits of Flex is its reach - the Adobe Flash Player, upon which Flex applications run, is already installed on most every computers.

In order to run our example we'll use Adobe Flex® Builder 3 software which is  a highly productive, Eclipse based development environment. You can try the evaluation version and then decide if you want to buy the license.

http://www.adobe.com/cfusion/entitlement/index.cfm?e=flex3email

 

Why developing in Flex when you have JSF ?

 

Both Flex and Java Server Faces are new technologies which still are still in evolution.

Flex strongest points include an easy to learn language, a good IDE if using commercial Flex-Builder tool, visual editing tools that look like it will be shown on the server, and extreme flexibility for giving a new look to existing legacy applications.

On the other hand JSF strengths are the excellent tools available in the market, the community size (developer base) and knowledge, lots of component libraries and AJAX support, a mature language, and an improved web framework for those who have been working in Java for some years and want to move to something better and easier than Struts.

It's difficult to evaluate which is the best choice, however as most of you certainly know, it's not always a matter of which framework is better in a real-life Project: it depends on the skills of your developers, on your company partnerships, sometimes even on personal tastes. So it's good to know a bit of both world, then you'll evaluate what's better for you.

 

Coding the Server Side

Ok, we'll cover first the server side which is a simple JAX-WS web service. 
This Web Service expose a method sayHello which returns a Person object created from the parameters (name and surname) passed.  

package sample;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.WebParam;

@WebService(name = "HelloWorld", targetNamespace = "http://webservice_consumer/helloworld")
public class HelloWorldWS
{
   @WebMethod
   public Person sayHello(String name,String surname)
   {

      String greeting = "Hello " + name + " -  " + surname;
      
      System.out.println(greeting);
      Person p = new Person();
      p.setName(name);
      p.setSurname(surname);
      
      return p;
      
   }

}

The class Person is a bare-bones Java Bean.

public class Person {

 private String name;
 private String surname;

 public String getName() {
    return name;
 }
 public void setName(String name) {
    this.name = name;
 }
 public String getSurname() {
    return surname;
 }
 public void setSurname(String surname) {
    this.surname = surname;
 }

}

Last piece of the webservice is the web.xml file which contains a standard mapping for the WebService:

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


<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">  
  <servlet> 
    <servlet-name>HelloWorldWS</servlet-name>  
    <servlet-class>sample.HelloWorldWS</servlet-class>  
  </servlet>  
  
  <servlet-mapping> 
    <servlet-name>HelloWorldWS</servlet-name>  
    <url-pattern>/HelloWorldWS</url-pattern> 
  </servlet-mapping>   
  
</web-app>
 

Ok, compile and package your webservice in a file named webservice_consumer.war

Building the Flex Tier


Ok now the Flex side: As we said Flex uses a declarative language (MXML) which has already many built-in functions. For our purpose we'll use the <mx:WebService> tag. It requires mainly to know the WSDL address of the Web Service.

<mx:WebService id="webService" wsdl="http://localhost:8080/webservice_consumer/HelloWorldWS?wsdl" >
     <mx:operation name="sayHello" resultFormat="object" result="display(event);">        
     
     <mx:request xmlns="" > 
 
        <arg0>Peter</arg0> 
        <arg1>Pan</arg1> 
 
      </mx:request> 

   </mx:operation> 
   
</mx:WebService>  

Inside the operation tag notice the following attributes: 

                resultFormat="object"
                result="display(event);"
                fault="displayfault(event);"

               
the first one instructs the compiler that the return type of the Web Service is a complex object. Then, with result, it instructs the compiler to invoke the "display" method when the operation is completed. In case of failure the "displayfault" method is triggered.

How do we code this methods ? simply using Action Script. ActionScript is a powerful object-oriented programming language executed by the ActionScript Virtual Machine (AVM) built into the Flash Player. For this sample we'll use just need to evaluate the result of the Web Service and populate a text field with its value.        

Then the <mx:request> tag is used to pass the actual parameters, name and surname. By the way ? how do you map your Flex parameters to Java parameters ? simply have a look at the WSDL of your Webservice. The two String parameters (name and surname) have beed defined as arg0 and arg1

<xs:complexType name="sayHello">
 <xs:sequence>
   <xs:element minOccurs="0" name="arg0" type="xs:string" />
   <xs:element minOccurs="0" name="arg1" type="xs:string" />
  </xs:sequence>
</xs:complexType>


So you simply pass them as:

 

    <arg0>   
         <name>Peter</name>
    </arg0>  
    <arg1>     
         <surname>Pan</surname>     
    </arg1> 


This is the full flex.mxml file.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white" viewSourceURL="srcview/index.html">

    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;
            import mx.rpc.events.ResultEvent;
            import mx.rpc.events.FaultEvent;
            import mx.utils.ObjectUtil;

            private var startTime:int;
            private var endTime:int;

            private function button_click():void {
                
                webService.sayHello.send();
                startTime = getTimer();
                lbl.text = "Wait.......";
            }

            private function display(evt:ResultEvent):void {
                textField.text = ObjectUtil.toString(evt.result.name);
                textField.text += ObjectUtil.toString(evt.result.surname);
                calcTime();
            }

            private function displayfault(evt:FaultEvent):void {
                Alert.show(evt.type);
                calcTime();
                lbl.text = "ERROR:::::";
            }

            private function calcTime():void {
                endTime = getTimer();
                lbl.text = "total time: " + (endTime - startTime) + "ms";
            }
        ]]>
    </mx:Script>

    <mx:WebService id="webService"
          wsdl="http://localhost:8080/webservice_consumer/HelloWorldWS?wsdl"
          useProxy="false">
                           
        <mx:operation name="sayHello"
                resultFormat="object"
                result="display(event);"
                fault="displayfault(event);">
            <mx:request xmlns="" >
                 <arg0>Peter</arg0>
                 <arg1>Pan</arg1>
            </mx:request>
        </mx:operation>
                                             
    </mx:WebService>
    <mx:Label text="Web Service output"/>
    <mx:TextInput id="textField"
            editable="false" />
    <mx:Spacer width="100%" />

    <mx:ApplicationControlBar dock="true">
        <mx:Button id="button"
                label="call web service"
                click="button_click();" />
        <mx:Label id="lbl" />
    </mx:ApplicationControlBar>

</mx:Application> 
 

Running the sample

In order to run the sample create a new Flex Project from the Menu:

jboss flex web services

You don't need to specify any Application Server, since you are using native Flex API for accessing Web Services. Now create a new MXML application from the main menu; paste the code in it.
 
jboss flex web services

To run the code, right-click on the source code and "Run As Flex Application"


If everything was completed successfully you should see the outoput from your Flex GUI

jboss flex web services

Special Thanks:
A special thank to Costantino Saponara who has helped me to get on working with the Flex environment. Thank you !

Related articles available on mastertheboss.com

JBoss web services

JAX-WS simplifies the development model for a web service endpoin

What is a Web Service One Way invocation?

JBoss recipe of the day

Asynchronous web services with JBoss WS

Developing rigorous and responsive web service client application

How to change the default Web Service deployment Port ?

JBoss recipe of the day

Using Axis Web Services with JBoss

Still not ready for JBoss WS ? if you don't have a JDK 1.5 compli

How do I know the WSDL URL of my Web Service ?

Ok supposing you have just deployed your Web Service application

Follow us on Twitter