Flex with Java Servlets: how to use XML from an HttpService to populate a Data Grid(Table)

April 20th, 2009 in Flex, Java/J2EE. 2 comments
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 4.00 out of 5)
Loading ... Loading ...

One of the ways to integrate a Java application with a Flex front end is by using Httpservice with XML. Aimed primarily at Java developers new to Flex, this quick start guide describes how to populate a flex table using xml returned by a servlet.
If you are looking create a Flex chart instead take a look a this tutorial:

Flex Chart from XML data using HttpService with Servlets

Steps:

  • First create the servlet: The following doPost method of the servlet just spits out an XML. In a real application, the XML will be returned from the business layer (but you already know that :) ).

    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       PrintWriter writer=response.getWriter();
    
       writer.println("<?xml version=\"1.0\"?>\n");
       writer.println("<salesdata>");
       writer.println("<item type=\"CDs\">");
       writer.println("<profit>");
       writer.println("  <beforetax>750</beforetax>");
       writer.println("  <aftertax>600</aftertax>");
       writer.println("</profit>");
       writer.println("<sales>1000.23</sales>");
       writer.println("</item>");
       writer.println("<item type=\"DVD\">");
       writer.println("<profit>");
       writer.println("  <beforetax>550.34</beforetax>");
       writer.println("  <aftertax>350.10</aftertax>");
       writer.println("</profit>");
       writer.println("<sales>1010.98</sales>");
       writer.println("</item>");
       writer.println("</salesdata>");
    }
    
  • Package the above servlet in a web app called FlexExample and map it to the pattern getData in web.xml.
  • Deploy the web app in tomcat and check if you see the xml by calling your servlet url (tomcathost:port/FlexExample/getData) from your browser.
  • In Flex Builder, create a new project and create a new MXML called FlexTest. Copy and Paste the following code. Pay particular attention to the highlighted sections, explanation follows:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
      <mx:Script>
       <![CDATA[
        import mx.rpc.events.ResultEvent;
        import mx.rpc.events.FaultEvent;
        import mx.controls.Alert;
    
        [Bindable]
        private var xmldata:XML;
    
       private function send_data():void {
             httpXmlDataService.send();
        }
    
       private function faultHandler(event:FaultEvent):void{
             mx.controls.Alert.show(event.fault.message,"Error in getting result");
        }
       private function resultHandler(event:ResultEvent):void{
            xmldata=event.result as XML;
       }
       private function displayBeforeTax(row:Object,column:DataGridColumn):String{
            return row.profit.beforetax;
       }
       private function displayAfterTax(row:Object,column:DataGridColumn):String{
            return row.profit.aftertax;
       }
       ]]>
     </mx:Script>
    
    <mx:HTTPService  id="httpXmlDataService"
            url="http://tomcathost:port/FlexExample/getData"
            resultFormat="e4x"
            result="resultHandler(event)"
            fault="faultHandler(event)"
            useProxy="false"/>
    <mx:Panel x="43" y="10" width="588" height="369" layout="absolute">
     <mx:DataGrid x="50" y="23" width="469" height="265" dataProvider="{xmldata.item}">
      <mx:columns>
       <mx:DataGridColumn headerText="Type" dataField="@type"/>
       <mx:DataGridColumn headerText="Sales" dataField="sales"/>
    
       <mx:DataGridColumn headerText="Profit before tax" labelFunction="displayBeforeTax"/>
       <mx:DataGridColumn headerText="Profit after tax" labelFunction="displayAfterTax"/>
      </mx:columns>
     </mx:DataGrid>
     <mx:Button x="66" y="296" label="Get Data" click="send_data()" />
    </mx:Panel>
    </mx:Application>
    
    1. lines 31-35: Defines the httpservice that we will be calling including the servlet url and the ActionScript functions that will be called upon success (resultHandler) or failure (faultHandler) of the service call. Also note that we have defined the resultFormat as e4x which makes XML handling easier (supposedly).
    2. lines 9-10: A variable, xmldata, of type XML is created and made ‘Bindable’ so that any assignments to it is detected wherever it is being used (in our case, in the datagrid).
    3. line 20: When the httpservice call returns successfully, the variable xmldata is assigned to the xml being returned from the service.
    4. line 38: The dataSource of the datagrid is set to xmldata.item. Note that the ‘item’ in xmldata.item refers to the ‘<item>’ node of the xml. Also note that the topmost tag- <salesdata> is not used.
    5. lines 40-41:Defines two of the columns- The first one (defined by dataField=”sales”) displays the value in the <sales> node which is the direct child of the <item> node of the xml. The other (defined by dataField=”@type”) displays the value of the type attribute of the <item> node;
    6. lines 43-44: Defines the other two columns that hold the children of the <profit> node- beforetax and aftertax. You can be forgiven for assuming that you should be able to use the dot operator to get the value of the child e.g “profit.beforetax”. Apparently that does not work. The attribute labelFunction needs to be used here and the functions called by it are described next.
    7. lines 22-23 and 25-26: Defines the functions called by the labelFunction attribute to obtain values in <beforetax> and <aftertax> nodes. Yes, you need to implement one for each non-direct children of <item>. Alternately, you may want to use the solution described here if your XML has too many children.
  • Now run the mxml file from Flex Builder and once it opens up in your browser click on the button to call the httpservice. You should see something like this:
    flexgrid Flex with Java Servlets: how to use XML from an HttpService to populate a Data Grid(Table)

The flash (.swf) file for the grid will be located in the bin-debug directory of your project in Flex Builder. This can be embedded into any webpage.

Related Articles

Flex Chart from XML data using HttpService with Servlets

Tags: , , , ,

2 Responses to “Flex with Java Servlets: how to use XML from an HttpService to populate a Data Grid(Table)”

  1. Rick at
    says:

    Nice clean explanation. Thanks. (I know there is BlazeDS now also, but was looking for an example just like this without using blazeDS.)

  2. Jonas Okwara at
    says:

    Awesome Explanation ! concise and Great tutorial !
    This is invaluable to some of us who want to incoporate Flex with servlets but cannot find books
    with this type of clarity

    thanks
    Jones

Leave a Reply

Sponsors