Sending data from flex to JSP using HTTPservice

November 20, 2007

Here is an example to post data from flex to JSP using httpservice. We’ll put a simple form under the data grid above to enter the data about the new employee and Pressing the Add Employee button will submit the entered data to the JSP, which will attach them to existing employees and return back so the data grid can be repopulated to include the newly inserted employee.

Here is code for Employee entry and Data grid.

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml&#8221; layout=”absolute” applicationComplete=”employees.send()”>
<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
{
return;
}
]]>
</mx:Script>

 

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

 

<mx:HTTPService id=”employees” useProxy=”false” method=”POST” url=”employee.jsp”/>
<mx:DataGrid dataProvider=”{employees.lastResult.people.person}” width=”50%”>
<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:Form width=”100%” height=”100%” x=”50″ y=”400″>
<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=”validateEmpName()”/>

</mx:Form>

</mx:Application> 

———————————————————————
here is code for employee.jsp
———————————————————————
<%
String employees=”<?xml version=\’1.0\’ encoding=\’UTF-8\’?><people><person><name>Alex</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>”;

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){
 out.println(employees+”</people>”);
}else{
 out.println(employees + newEmployee + “</people>”);
}
%>

Advertisements