Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Expo on Google News

SYS-CON.TV
Cloud Expo & Virtualization 2009 East
PLATINUM SPONSORS:
IBM
Smarter Business Solutions Through Dynamic Infrastructure
IBM
Smarter Insights: How the CIO Becomes a Hero Again
Microsoft
Windows Azure
GOLD SPONSORS:
Appsense
Why VDI?
CA
Maximizing the Business Value of Virtualization in Enterprise and Cloud Computing Environments
ExactTarget
Messaging in the Cloud - Email, SMS and Voice
Freedom OSS
Stairway to the Cloud
Sun
Sun's Incubation Platform: Helping Startups Serve the Enterprise
POWER PANELS:
Cloud Computing & Enterprise IT: Cost & Operational Benefits
How and Why is a Flexible IT Infrastructure the Key To the Future?
Click For 2008 West
Event Webcasts
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 

About 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. Yakov co-athored the O'Reilly book "Enterprise Application Development with Flex". He twits at twitter.com/yfain.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

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.

plz send the info regarding the
struts with flex

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.


Your Feedback
Yakov wrote: 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 wrote: plz send the info regarding the struts with flex
JDJ News Desk wrote: 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.
Latest Cloud Developer Stories
Swisscom, the Swiss telecom, is going into the cloud business. Its subsidiary Swisscom IT Services AG has signed up with Red Hat as a Certified Cloud Provider and launched a public cloud Infrastructure-as-a-Service (IaaS) cloud targeting enterprise-class customers primarily in ...
Apache Deltacloud, the Red Hat-contributed ReSTful API that abstracts differences between clouds so services on any cloud can be managed – provided of course there’s a driver – has graduated from the Apache Foundation’s incubator and is now a full-fledged Top-Level Project (TLP)....
In a surprise move on Tuesday, January 10, Oracle wheeled out its Big Data Appliance. That’s the one it said in October would be ready sometime in the first half. Only nobody believed it meant early in the first half. Heck, it’s not even clear anybody thought Oracle could make ...
Rackspace Hosting, the service leader in cloud computing, on Thursday announced its acquisition of SharePoint911, an industry leader in SharePoint consulting, training, and "JumpStart" services within SharePoint. The unification of both companies provides capabilities to deliver ...
CloudLinux, Inc., on Thursday released CafeFS 3, a virtualized file system for shared hosters that cages each customer within its own virtualized file system. CageFS becomes part of CloudLinux OS at no additional charge. CloudLinux OS, the only commercially-supported Linux OS m...
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON Featured Whitepapers
ADS BY GOOGLE

Breaking Cloud Computing News

The Khronos™ Group, an industry consortium creating open standards for the accelera...