The No.1 i-Technology Magazine in the World !
   
 

      ES no BS
This is a personal blog of Yakov Fain       My son's animations and music         No BS IT podcast      Америчка




Archives

««Sep 2010»»
SMTWTFS
    1
2
34
567891011
12131415161718
19202122232425
2627282930

RSS Feed








Subscribe to these blogs

Sending data from Flex to a JavaServer Page

posted Wednesday, 3 January 2007

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 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    




1. Rauf left...
Thursday, 4 January 2007 4:49 pm

Hi Yakov,

I am a 'recreational' java designer/developer; meaning, I don't do this for living. I have been debating myself for quite some time whether to give Flex a try or not. Flex licensing cost is does not help in this decision process :-) I have experimented with AJAX a little bit and not happy with the amount of memory it eats up in the client machine.

My two questions:

1. Are there any deployments out there that use Flex for the RIA or this is still at the infancy level? 2. When a client accesses a Flex based application on the app server for the first time, does the client has to download any module from Adobe servers? I am thinking since using flash requries a Flash player to be downloaded; Flex would probably be the same!

thanks

Rauf


2. Yakov Fain left...
Thursday, 4 January 2007 5:30 pm

Rauf,

This and the prior blog are written for people who for any resaon do not want to pay anything, but have Flash as a front end for their Java Web applications. I'm not saying that this is the best way, but it's definitely the cheapest way. Flex is young, but it's real - I'm earning half of my income doing Flex for Wall Street clients. The other half is Java. When the client aceeses an application written in Flex (a compiled .swf file), they just need to have Flash Player installed, which happens seamlessly and quickly (something that Java was not able to pull off till today). Your Flash Player has no clue if you programmed your app in pure ActionScript, Flex or Open Laszlo. For more technical stuff on Flex, read our blog dedicated to Flex: flexblog.faratasystems.com.

Should I recommend you learning Flex? I have mixed fillings. If you become Flex programmer, you'll start competing with me, and my rates will go down. On the other hand, the more people know Flex, the more new projects will open up, and I'll have more gigs. You know what, just keep sitting on the fence for another year while I'll take care of my retirement using Flex :)


3. Murat left...
Friday, 5 January 2007 5:37 am

Ok flex really looks promising but i wonder if it is really safe? It is possible (actually simple) to save and decompile applet classes and flash swfs on the client side. If the client can access your flex code then they can find out to call which method or even bypassing several calls. If so I think the client side should be more like an remote interface or a facade to some services other than having logical code. I really wonder about the code security of flex???


4. Yakov Fain left...
Friday, 5 January 2007 7:40 am

Murat,

Flex code is compiled into a bytecode (like Java). It runs in a VM - Flash Player 9, that has JIT compiler that turns 99% of it into a machine code. Flash Player's sandbox security model is somewhat similar to Java. You suggestion of usint it as a facade is not right - Flax is a tool for creation of rich (fat) clients that run on the client machine with easy integration with J2EE or other Web technologies. This blog does not explain the proper integration with Java, it's just shows a poor man's version of it - connection to a JSP.


5. Murat left...
Friday, 5 January 2007 9:21 am

Dear Yakov,

Actually it is easy to decompile class or swf but if you say flex is safe, that more than enough for me, since you are my java hero :) I have very little experince with flex but I totaly agree that it is the best solution for rich clients right now (also for a java developer)..

Thanx Murat


6. Yakov Fain left...
Friday, 5 January 2007 9:36 am

"it is easy to decompile class or swf..."

It's easy to kill a man too - just get a sharp knife...But I am talking about conventional way of programming done by developers, not hackers. But if you take Ajax, you do not even need to decompile anything - just do a right-click and View Source (unless they applied some obfuscators, of course)


7. Murat left...
Saturday, 6 January 2007 12:54 pm

Absolutely Ajax is not even a point :) thx


8. Yogesh left...
Wednesday, 4 July 2007 7:07 am

Hi discription is good. but u r not mention the configuration of the file. where we kept this file,in which folder.