Welcome!

Adobe Flex Authors: Liz McMillan, RealWire News Distribution, Maureen O'Gara, Yakov Fain, Keith Swenson

Related Topics: Java, ColdFusion, Adobe Flex

Java: Article

Sending Data From Flex to a JavaServer Page

We'll send data from a Flex application played by Flash Player to a Java Server Page

From Farata Systems  Blog

This is a part two of the prior blog where I described how to get data from JSP to Flex. This time we'll send data from a Flex application played by Flash Player to a Java Server Page. In the next version of our Flex-JSP application I’ll show you how to post data from a Flex form to JSP. We’ll place a simple form under the data grid above to enter the data about the new employee as in Figure below. Pressing the button Add Employee will submit the entered data to the JSP, which will attach them to existing employees and  return back so the data grid will be repopulated to include the newly inserted employee.

To design the form, we’ll be using Flex objects <mx:Form> container, which differs from the HTML tag <form>. The latter is an invisible container that holds some data, while <mx:Form> is used to arrange on the screen input controls with their labels.  We’ll also use <mx:Model> to store the data bound to our <mx:Form>.  Let’s also make the employee name a required field and add so called validator to prevent the user from submitting the form without entering the name. It will look as follows:

<mx:StringValidator id="empNameVld" source="{empName}" property="text" />

  <mx:Model id="employeeModel">
   <root>
     <empName>{empName.text}</empName>
     <age>{age.text}</age>
     <skills>{skills.text}</skills>
   </root>
  </mx:Model>

<mx:Form width="100%" height="100%">
  <mx:FormItem label="Enter name:" required="true">
     <mx:TextInput id="empName" />
  </mx:FormItem>
    <mx:FormItem label="Enter age:">
     <mx:TextInput id="age" />
  </mx:FormItem>
  <mx:FormItem label="Enter skills">  
     <mx:TextInput id="skills" />
  </mx:FormItem>
  <mx:Button label="Add Employee" click="submitForm()"/>
</mx:Form>


The attribute required=true displays a red asterisk by the required field but does not do any validation. The <mx:StringValidator> displays the prompt “This field is required” and  makes the border of the required field red if you move the cursor out of the name field while it’s empty, and shows a prompt when you return to this field again as in Figure below. But we’d like to turn off this default validation by adding the property triggerEvent with a blank value:

  <mx:StringValidator id="empNameValidator" source="{empName}"
                                   property="text"  triggerEvent=""/>

We’ll also add our own AS3 function validateEmpName(). Now the click event of the Add Employee button  will call validateName(), which in turn will either call the function submitForm() if the name was entered, or display a message box "Employee name can not be blank" otherwise.

Validators are outside of the scope of this chapter, and we’ll just mention that Flex comes with a number of pre-defined classes that derived from the base class Validator. They ensure that the input data meet certain rules. The names of these classes are self explanatory: DateValidator, EmailValidator, PhoneNumberValidater, NumberValidator, RegExValidator, CreditCardValidator, ZipCodeValidator and StringValidator. These validators work on the client side, and round trips to the server are not required. A program initiates the validation process either as a response to an event or by direct call to the  method validate() of the appropriate validator instance as shown below.

The final version of the Flex portion of our application is shown below.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
                             applicationComplete="employees.send()">
    <mx:HTTPService id="employees" useProxy="false"  method="POST"
       url="http://localhost:8080/test/employees.jsp" result="onResult(event)" />

    <mx:DataGrid dataProvider="{employees.lastResult.people.person}" width="100%">
          <mx:columns>
            <mx:DataGridColumn dataField="name" headerText="Name" />
            <mx:DataGridColumn dataField="age" headerText="Age"/>
            <mx:DataGridColumn dataField="skills" headerText="Skills"/>                        
         </mx:columns>
    </mx:DataGrid>

  <mx:StringValidator id="empNameValidator" source="{empName}"
                                   property="text"  triggerEvent=""/>
  <mx:Model id="employeeModel">
   <root>
     <empName>{empName.text}</empName>
     <age>{age.text}</age>
     <skills>{skills.text}</skills>
   </root>
  </mx:Model>

<mx:Form width="100%" height="100%">
  <mx:FormItem label="Enter name:" required="true">
     <mx:TextInput id="empName" />
  </mx:FormItem>
    <mx:FormItem label="Enter age:">
     <mx:TextInput id="age" />
  </mx:FormItem>
  <mx:FormItem label="Enter skills">  
     <mx:TextInput id="skills" />
  </mx:FormItem>
  <!--mx:Button label="Add Employee" click="submitForm()"/-->
  <mx:Button label="Add Employee" click="validateEmpName()"/>  
</mx:Form>

 <mx:Script>
 <![CDATA[

  import mx.events.ValidationResultEvent;
  import mx.controls.Alert;
  private function validateEmpName():void{
   if (empNameValidator.validate().type == ValidationResultEvent.VALID){
            submitForm();     
   } else{
         Alert.show("Employee name can not be blank");
   }
  }

 private function submitForm():void {
  employees.cancel();
  employees.send(employeeModel);
 }
 
private function onResult(event:Event):void{
    trace('Got the result'); // works only in the debug mode
    return;
  }
 ]]>
 </mx:Script>
</mx:Application>


When the user hits the button Add Employee on the form, our HTTPService will submit the employeeModel to a modified employees.jsp, which now will get the parameters from the HTTPRequest object, prepare the new XML element newNode  from the received data, concatenate it to the original three employees, and return it back to the client, which will display all employees in the datagrid.  Here’s the new version of employee.jsp:


<%
String employees="<?xml version=\"1.0\" encoding=\"UTF-8\"?><people><person><name>Alex Olson</name><age>22</age><skills>java, HTML, SQL</skills></person><person><name>Brandon Smith</name><age>21</age><skills>PowerScript, JavaScript, ActionScript</skills></person><person><name>Jeremy Plant</name><age>20</age><skills>SQL, C++, Java</skills></person>";
    
   // Get the parameters entered in the GUI form
   String name=request.getParameter("empName");
   String age=request.getParameter("age");
   String skills=request.getParameter("skills");
   String newEmployee="<person><name>" + name+ "</name><age>" + age + "</age><skills>"
                                     + skills +"</skills></person>";
   if (name == null){
      newEmployee="";
   }
   // the xml goes back to the Web browser via HTTPResponse
   out.println(employees + newEmployee + "</people>");
%>


Figure. The employee form and default  validator’s message

Note: There are other ways to pass the data from Flex to an existing server side Web application. For example, you can create an instance of the URLVariables object, create the data to be passed as its properties, attach URLVariables to URLRequest.data and call navigateToURL().

tags:      
links: digg this    del.icio.us    technorati 

More Stories By Yakov Fain

Yakov Fain is a Managing Director of Farata Systems, consulting, training and product company. He has authored several Java books, dozens of technical articles. SYS-CON Books released his latest co-authored book , Rich Internet Applications with Adobe Flex and Java: Secrets of the Masters in Spring 2007. Sun Microsystems has nominated and awarded Yakov with the title Java Champion. He leads the Princeton Java Users Group. He is an Adobe Certified Flex Instructor. Currently Yakov works on the book for O'Reilly "Enterprise Application Development with Flex". He twits at twitter.com/yfain.

Comments (3) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Yakov 01/09/07 11:35:31 PM EST

When you use Flex, struts is not needed. Download our presentation (see archives) at New JavaSIG (http://www.javasig.com/) - there are several slides proving this.

tushar mali 01/09/07 03:48:42 AM EST

plz send the info regarding the
struts with flex

JDJ News Desk 01/03/07 01:45:53 PM EST

This is a part two of the prior blog where I described how to get data from JSP to Flex. This time we'll send data from a Flex application played by Flash Player to a Java Server Page. In the next version of our Flex-JSP application I?ll show you how to post data from a Flex form to JSP. We?ll place a simple form under the data grid above to enter the data about the new employee as in Figure below. Pressing the button Add Employee will submit the entered data to the JSP, which will attach them to existing employees and return back so the data grid will be repopulated to include the newly inserted employee.