SYS-CON Media
 Register Now!
Save $200
Register before October 17th to SAVE! ... and also receive a FREE copy of the Best-Selling AJAX Book, a $119 Value!
Untitled Document
2008 East
Platinum Sponsor
Untitled Document
2008 East Gold Sponsors
Untitled Document
2008 East Exhibitors
Untitled Document
2008 East Media Sponsors
Untitled Document
2008 Association Sponsor
SYS-CON Media
2007 West Sponsors
Goingtomeet.com Conference Directory
SYS-CON Media
2007 East Sponsors
Untitled Document
2008 SYS-CON Events

Can't Miss RSS Feed
Subscribe to the AJAXWorld.com RSS Feed & Get All The Conference News As It Happens!

2008: Decision Year for RIAs - October 20-22, 2008 San Jose


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 Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @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.


Latest AJAXWorld RIA Stories
Your job is mostly boring. Many of the IT operations tasks you perform on a day-to-day basis are repetitive and dull. Utilizing automation can improve your work life, automating away the drudgery and embracing the passion for technology that got you started in the first place. In...
Technological progress can be expressed as layers of abstraction - higher layers are built on top of lower layers treating them as abstract black boxes with known interfaces. A serverless approach represents an inflection point that entirely separates the runtime layer from the u...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks w...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO Silicon Valley 2019 will cover all of these tools, with the most comprehensive program and with 222 rockstar speakers throughout our industry presenting 22 Keynotes and General Sessions, 250 Breakout Sessions along 10 Tracks, as well as our ...
Big Switch's mission is to disrupt the status quo of networking with order of magnitude improvements in network e ciency, intelligence and agility by delivering Next-Generation Data Center Networking. We enable data center transformation and accelerate business velocity by delive...
Untitled Document

Call 201 802-3020 or Click Here to Save $200!

Register Today and
Save $200

Your registrations includes: Golden Pass Delegates will receive full conference access on October 20-22, 2008 including: Lunch and Coffee Breaks, Collectible Bag and Archives of all sessions on DVD. Includes access to all Conference Sessions including the Technical Sessions, Exhibits, Keynotes, Vendor Technology Presentations, and Power Panels.


Sponsorship Opportunities

AJAXWorld offers the undisputed best platform to position your company as a leading vendor in the fast-emerging marketplace for AJAX and Enterprise Web 2.0.


Please call
(201)802-3020


Who Should Attend?

 CTOs & VPs of Engineering
 Directors of Technology
 Sr. User Interface Architects
 Front-End Engineers
 VCs & Industry Analysts
 Directors of Business Development
 Software Engineers
 Senior Architects
 Application Programmers & Software Developers
 Project Managers
 Web Programmers & Designers
 Companies & Organizations that need to stay in
  front of the latest Web technology

AJAXWorld Security Bootcamp

Introducing at AJAXWorld RIA Conference 2008 West the world's first-ever full, one-day immersive "AJAX Security Bootcamp" - led by one of the world's foremost AJAX security experts and teachers, HP's Billy Hoffman.

View the full one-day schedule



AJAXWorld 2008 West - Tracks

Track 01: Enterprise RIAs
Track 02: Frameworks & Toolkits
Track 03: Web 2.0 & Mashups
Track 04: Hot Topics
Track 05: The Future of the Web
Track 06: iPhone Developer Summit



Brought To You By:

AJAXWorld Magazine is the pre-eminent independent vendor-neutral resource for the fastest growing new segment of the software business: entirely Web-based applications and experiences.

Download the Latest Issue!

AJAXWorld Webcasts



SYS-CON EVENTS


AJAXWorld Keynotes & Power Panels

2008 SYS-CON TV Keynotes: Can We Fix the Web? By Douglas Crockford - by Douglas Crockford
2008 SYS-CON TV Keynotes: 2008: The Year of the RIA - by Anthony Franco
2008 SYS-CON TV Power Panel: The Business Value of RIAs
2008 SYS-CON TV Power Panel: What Lies Beyond AJAX
2007 SYS-CON TV Keynotes: Why Web 2.0 for the Enterprise Is Far More Than Just a Facelift - by Ted Farrell
2007 SYS-CON TV Keynotes: Fueling the Next Generation Web: A Peek Behind the Green Curtain - by Bob Brewin
2007 SYS-CON TV Keynotes: AJAX in the Balance - by Joe Stagner

AJAXWorld Sessions on SYS-CON.TV

· Bill Scott - Yahoo! UI Library
· David Heinemeier Hansson - AJAX on Rails
· Jesse James Garrett - Elements of User Experience
· Dion Hinchcliffe - Real World AJAX
· Eric Miraglia - Open Source AJAX Development
· Paul Rademacher - Mashing Up Your Web Application
· Adam Sah - Google Gadgets
· Doug Crockford - An Introduction to JavaScript
· David Linthicum - Enterprise Web 2.0
· Patrick Grady - The Imagination & Experience Web

AJAXWorld...All The AJAX Rock Stars in One Spot!


Past Events Archive

SOAWorld Conference & Expo 2008 East
soa2008east.sys-con.com
Virtualization Conference & Expo 2008 East
virt2008east.sys-con.com
AJAXWorld 2008 Conference & Expo East
ajaxmar08.sys-con.com
SOAWorld Conference & Expo 2007 West
www.soaworld2007.com
Virtualization Conference & Expo 2007 West
virt2007west.sys-con.com
AJAXWorld 2007 Conference & Expo West
ajaxoct07.sys-con.com
SOAWorld Conference & Expo 2007 East
soa2007east.sys-con.com
Virtualization Conference & Expo 2007 East
virt2007east.sys-con.com
AJAXWorld 2007 Conference & Expo East
ajaxmarch07.sys-con.com
Other SYS-CON Events
events.sys-con.com

Join Over 10,000 Early AJAX Adopters
Who Have Attended AJAXWorld
• A&R Edelman
• Academic Enterprise
• Accoona Corp [2 delegates]
• Acxiom
• Adams Capital Management
• Adaptive Edge
• Adaptive Path
• Adobe Systems Incorporated [21 delegates]
• Adobe Systems Romania
• Ajax13
• All Risks, Ltd.
• alliance
• Alliance For Community Care
• AlphaDetail Inc
• Altera Corporation
• Amazon.com [6 delegates]
• Appeon Corporation [2 delegates]
• Apple Computer [5 delegates]
• Apress [3 delegates]
• Arkivio
• ASA
• Astute Solutions
• Avaya Inc [2 delegates]
• Avenda Systems
• Avenue A | Razorfish [3 delegates]
• Axcella, LLC [2 delegates]
• Aximsoft
• Azimyth
• Backbase USA Inc. [4 delegates]
• BAE Systems [2 delegates]
• Bank of America [2 delegates]
• Barkley Evergreen & Partners Interactive
• Bayview Financial [2 delegates]
• BEA Systems [3 delegates]
• Billeo
• BMC Software, Inc. [2 delegates]
• Borland Software Corporation
• Bradford Technologies, Inc [2 delegates]
• Brilliance
• Brocade Communications Systems, Inc. [2 delegates]
• Brookside Capital LLC
• Brulant
• Bungee Labs, Inc [6 delegates]
• Bureau of Labor Statistics
• BUZ Interactive
• Cadena Software
• Calix Networks
• Callidus Software [2 delegates]
• Cambia Security
• Carnegie Mellon West
• Cautella, Inc.
• CBSA
• Celequest [3 delegates]
• Change Vision, Inc.
• Charles E. Kenney, CPA
• Charles Schwab & Co., Inc. [8 delegates]

   read more...


ADVERTISE   |   MAGAZINE SUBSCRIPTIONS   |   FREE BREAKING-NEWSLETTERS!   |   SYS-CON.TV   |   BLOG-N-PLAY!   |   WEBCAST   |   EDUCATION   |   RESEARCH

.NET Developer's Journal - .NETDJ   |   ColdFusion Developer's Journal - CFDJ   |   Eclipse Developer's Journal - EDJ   |   Enterprise Open Source Magazine - EOS
Open Web Developer's Journal - OPEN WEB   |   iPhone Developer's Journal - iPHONE   |   Virtualization - Virtualization   |   Java Developer's Journal - JDJ   |   Linux.SYS-CON.com
PowerBuilder Developer's Journal - PBDJ   |   SEO / SEM Journal - SJ   |   SOAWorld Magazine - SOAWM   |   IT Solutions Guide - ITSG   |   Symbian Developer's Journal - SDJ
WebLogic Developer's Journal - WLDJ   |   WebSphere Journal - WJ   |   Wireless Business & Technology - WBT   |   XML-Journal - XMLJ   |   Internet Video - iTV
Flex Developer's Journal - Flex   |   AJAXWorld Magazine - AWM   |   Silverlight Developer's Journal - SLDJ   |   PHP.SYS-CON.com   |   Web 2.0 Journal - WEB2

SYS-CON MEDIA:   ABOUT US   |   CONTACT US   |   COMPANY NEWS   |   CAREERS   |   SITE MAP
SYS-CON EVENTS  |  AJAXWorld Conference & Expo  |  iPhone Developer Summit  |  OpenWeb Developer Summit  |  SOA World Conference & Expo  |  Virtualization Conference & Expo
INTERNATIONAL SITES:   India  |  U.K.  |  Canada  |  Germany  |  France  |  Australia  |  Italy  |  Spain  |  Netherlands  |  Brazil  |  Belgium
 Terms of Use & Our Privacy Statement     About Newsfeeds / Video Feeds
Copyright ©1994-2008 SYS-CON Publications, Inc. All Rights Reserved. All marks are trademarks of SYS-CON Media.
Reproduction in whole or in part in any form or medium without express written permission of SYS-CON Publications, Inc. is prohibited.