Pages

Thursday, May 20, 2010

Flex Http Service

Share it Please


Flex was one of the best framework for developing RIA [ Rich Internet Applications ]. it provides many inbuilt capabilites for connecting to various back end systems including Http and SOAP based web-services.

in this article , we will see how we can connect to a java servlet using flex HttpService.this service does not require any changes to any configuration files.

HttpService - Using Flex Http Service we can send request for getting external data either using post or get methods. we can use HttpSerivce with any kind of backend technology like Java Server pages ,ColdFusion , Microsoft Asp.net e.t.c.

Creating A Flex User Interface - we will make our example very simple .we will create a Text Field which accepts a String and a Button which shows the length of the text entered by making a call to server .



here is the Mxml Code for creating the Layout

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
  
<mx:HTTPService id="serverCall" method="POST"  
    url="http://localhost:8080/HttpServiceInFlex/SampleHttpServlet"
    result="on_Result(event)" fault="on_Fault(event)"/>

<mx:TextInput x="47" y="17" text="Enter Your Name Here" id="textInput"/>
<mx:Button x="47" y="47" label="Call Servlet" id="callToServer" click="send_data(event)"/>    
  
    <mx:Script>
        <![CDATA[
            import mx.rpc.events.FaultEvent;
            import mx.rpc.events.ResultEvent;
             import mx.controls.Alert;
          
            private function send_data(event:MouseEvent):void {
                var param:Object = {};
                param["name"] = textInput.text;
                serverCall.send(param);
            }
          
            private function on_Result(event:ResultEvent):void {
                Alert.show(event.message.body.toString());
            }
          
            private function on_Fault(event:FaultEvent):void {
                Alert.show(event.toString(), event.type);            
            }
          
        ]]>
    </mx:Script>
      
</mx:Application>

lets see the main parts in the code , a HttpService can be created by Using <mx:HTTPService> element like

<mx:HTTPService id="serverCall" method="POST"  
    url="http://localhost:8080/HttpServiceInFlex/SampleHttpServlet"
    result="on_Result(event)" fault="on_Fault(event)"/>

HttpService takes a few properties lik id="serverCall" which we will be using when making a call to java servlet and to send some parameters to server side.
method="get" - the method we are requesting
url=Url is the page we are trying to access
we will also define result and fault event handlers which are invoked when a call to server succeds or fails.

and  now coming to the actionScript code ,
we have written a send_data() method which gets invoked when we click the button under the text Field. so we define the send_data() method as


private function send_data(event:MouseEvent):void {
                var param:Object = {};
                param["name"] = textInput.text;
                serverCall.send(param);
      }

here we are using
var param:Object = {};

param["name"] = textInput.text; to get the value from textField and assign to the variable "name" and keep that in the request .

serverCall.send(param);  , in this we are invoking the call to the server by passing the values that are collected from the textField.

the other 2 methods ,

private function on_Result(event:ResultEvent):void {
                Alert.show(event.message.body.toString());
}
          
private function on_Fault(event:FaultEvent):void {
                Alert.show(event.toString(), event.type);            
}

which are nothing but the event handlers for handling the status returned by the HttpService .if there is a success then the on_Result method is invoked which alerts the response obtained  and fault does the thing that is defined for handling fault events.

here comes the SampleServlet that i Used

package com.HttpService;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SampleHttpServlet
 */
public class SampleHttpServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
     
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SampleHttpServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sentvalue=request.getParameter("name");
        response.getWriter().append("Your Name Contains Total "+sentvalue.length()+" characters");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sentvalue=request.getParameter("name");
        response.getWriter().append("Your Name Contains Total "+sentvalue.length()+" characters");
    }

}

Just takes the String and counts the number of characters in the String.

and finally we are done with code ,  lets see how it works




We will see some more ways of connecting to back ends using Flex in the next articles

Happy Coding
…………

No comments :

Post a Comment