Sending data from Flex to a JavaServer Page

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().

Yours truly,

Yakov Fain

One thought on “Sending data from Flex to a JavaServer Page

  1. hello sir,
    i am getting error after running your given example of send data from flex to jsp . the error is i.e.

    [RPC Fault faultString=”HTTP request error” faultCode=”Server.Error.Request” faultDetail=”Error: [IOErrorEvent type=”ioError” bubbles=false cancelable=false eventPhase=2 text=”Error #2032: Stream Error. URL: http://localhost:8080/employees.jsp“]. URL: http://localhost:8080/employees.jsp“]
    at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::faultHandler()
    at mx.rpc::Responder/fault()
    at mx.rpc::AsyncRequest/fault()
    at ::DirectHTTPMessageResponder/errorHandler()
    at flash.events::EventDispatcher/flash.events:EventDispatcher::dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at flash.net::URLLoader/flash.net:URLLoader::redirectEvent()

    please send solution if you know or any alternate
    thanks
    pankaj

Comments are closed.