Archive

Posts Tagged ‘Request & Response data communication’

URL loader frowns “when HttpService does, why cant I ?”

May 19, 2009 4 comments

URL loader allows the users to handle requests and response to and from HttpServices same as what flex HttpService allows the users to do. So whatever the task can be done by HttpService, can also do by URL loader but the way they do will be different. We do have MXML HttpService tag which will invoke HttpServices like servlet in a much easier way than URL loader. Because we dont have MXML URL loader tag since its part of Flash player API so we can create an URL loader instance and call servlet using ActionScript alone.

To invoke a servlet using load method of URLLoader instance, the load method will expect a single parameter which is none other than URLRequest instance. It defines the URL in which it will request the servlet when URLLoader instance invokes the load method. As well as the event handler function for URLLoader complete event should be registered before you invoke the servlet because as you know well this event handler function will be executed once the request has been fulfilled.


var loader : URLLoader = new URLLoader();
var request : URLRequest = new URLRequest("http://localhost:8080/CallServlet/callService");
loader.addEventListener(Event.COMPLETE,resultHandler);
loader.load(request);

When we make a request to the servlet, we should also send request parameters which will be expected by the servlet when it receives the request. In URL loader we do have class named URLVariables through which we will create the request parameters as name/ value pair and finally we will set the data property of the URLRequest instance to URLVariables instance.


var param :URLVariables = new URLVariables();
param.email = email.text;
param.pass = pass.text;
request.data = param;

Thats it. Now replace the URLLoader instance code, instead of HttpService instance code in our previous example & run the application.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="createLoader()">

 <mx:Script>
 <!&#91;CDATA&#91;
 import mx.rpc.events.FaultEvent;
 import mx.rpc.events.ResultEvent;
 import mx.controls.*;

 var loader : URLLoader;
 var request : URLRequest;

 public function createLoader():void
 {
 loader = new URLLoader();
 request = new URLRequest("http://localhost:8080/CallServlet/callService");
 loader.addEventListener(Event.COMPLETE,resultHandler);
 }
 public function callLoader():void
 {    
 var param :URLVariables = new URLVariables();
 param.email = email.text;
 param.pass = pass.text;
 request.data = param;
 loader.load(request);
 }
 public function resultHandler(event : Event):void
 {
 Alert.show(loader.data);
 }
 public function faultHandler(event : Event):void
 {
 Alert.show("error");
 }
 &#93;&#93;>
 </mx:Script>

 <!--<mx:HTTPService id="service" url="http://localhost:8080/CallServlet/callService" result="resultHandler(event)" fault="faultHandler(event)" method="GET" showBusyCursor="true" resultFormat="text">
 <mx:request xmlns="">
 <email>{email.text}</email>
<pass>{pass.text}</pass>
 </mx:request>
 </mx:HTTPService> -->

 <mx:Panel paddingLeft="20" paddingRight="20" paddingTop="20" paddingBottom="20">
 <mx:FormItem label="E-mail">
 <mx:TextInput id="email" />
 </mx:FormItem>
 <mx:FormItem label="Password">
 <mx:TextInput id="pass" displayAsPassword="true" />
 </mx:FormItem>
 <mx:Button label="Submit" click="callLoader()" />
 </mx:Panel>

</mx:Application>

Download previous example here

Note :

This post is continuity of my previous post if you could not follow this instructions. Please refer my previous post click here. Still you could not follow, drop your feedback i will try to refine the content as much as possible.

Advertisements

HttpService says “I can invoke the servlet”

May 18, 2009 9 comments

Hi everybody, its my pleasure to come up with another interesting blog that is how to invoke a servlet from flex application using HttpService. Let me start with HttpService which is responsible for handling request and response to and from http services like servlet. Now we are bound to know how servlet works, dont get panic !!! its easy let me explain.

Servlet – a glance

Whenever the client requests resource from web server (Apache), the web server will fetch the resource and send it as a response to the client. But the web server will love to serve as long as the requested resource is static content. If the client request any dynamic content which will not be available until the request is made, the web server cant do it alone so that it need help from some helper application like servlet which is capable of generating just in time resource i.e. dynamic content.

Who is the manager of servlet ?

Now you must know the person who is managing servlet who is none other container. the role of container has to create an instance of servlet before any one requests the servlet and whenever the client requests the servlet the container will intercept and create new thread of the requested servlet and also it will handover the request parameters to the servlet class

Note :

One could not explain the concept of servlet and container in single post because its too vast, i hereby just given idea about servlet and how it works. If you want to know more there are plenty of forums available where you can know everything about these stuffs.

Now come back to our concept. To invoke a servlet from flex you have to create HttpService component, Servlet class and at last you have to map the URL to Servlet in deployment descriptor.

Before you do all these stuffs, set up your web application in Tomcat , create flex project and configure server location of your flex application. Please refer to my previous post if you dont know how to do it, click here

Create HttpService component

  • Create HttpService instance in your MXML application file, name the instance and define the event handler function name for result and fault property.
  • specify the url which will invoke the servlet class when user invokes the service.
  • Define the http method of your request e.g. GET, POST etc.
  • Specify the request parameters of your HttpService which will passed to the servlet and servlet will do some process with the data. It can be specified using request property of HttpService.
  • Define the event handler function for result and fault inside <mx:script> tag.
  • The response of the servlet will be handled by either result event handler function or fault event handler function depends on the result of servlet invocation.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">

 <mx:Script>
 <!&#91;CDATA&#91;
 import mx.rpc.events.FaultEvent;
 import mx.rpc.events.ResultEvent;

 import mx.controls.*;

 public function resultHandler(event : ResultEvent):void
 {
 Alert.show(event.result.toString());
 }

 public function faultHandler(event : FaultEvent):void
 {
 Alert.show("error");
 }

 &#93;&#93;>
 </mx:Script>

 <mx:HTTPService id="service" url="http://localhost:8080/CallServlet/callService" result="resultHandler(event)" fault="faultHandler(event)" method="GET" showBusyCursor="true" resultFormat="text">
 <mx:request xmlns="">
 <email>{email.text}</email>
<pass>{pass.text}</pass>
 </mx:request>
 </mx:HTTPService> 

 <mx:Panel paddingLeft="20" paddingRight="20" paddingTop="20" paddingBottom="20">
 <mx:FormItem label="E-mail">
 <mx:TextInput id="email" />
 </mx:FormItem>
 <mx:FormItem label="Password">
 <mx:TextInput id="pass" displayAsPassword="true" />
 </mx:FormItem>

 <mx:Button label="Submit" click="service.send()" />
 </mx:Panel>

</mx:Application>
 

In the code you are seeing above, i just created HttpService instance and the request parameter are the users input of email address and password which will be passed to servlet once the user invokes servlet by clicking “Submit” button.

Create, compile & deploy servlet

  • Create a java class which should extend HttpServlet Class
  • Define doGet method if you have declared GET in the method property of HttpService instance else doPost.
  • Get the request parameters sent by the HttpService instance
  • Do some process with request parameters
  • Compile the servlet class
  • Finally copy your_servlet.class and paste this file in to {Tomcat_home_directory}\webapps\{Web_application_name}\WEB-INF\classes folder of your web application.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
String email = request.getParameter("email");
String password = request.getParameter("pass");
String result = "Hi iam servlet, I am here to conform your username & password, they are " + email + " & " + password + ". is it correct ?";
PrintWriter out = response.getWriter(); out.println(result);
}
}

In the servlet class above, i have implemented doGet() method since i have declared GET in the method property of HttpService instance. I am also getting the request parameters , construct a string which asks user whether the email address and password they have entered are same as it displays and finally it returns that string as response to the HttpService request.

Map URL to servlet

Actually the servlet will have three names. They are public URL, internal name and actual servlet path . The public URL and internal name wont be necessary to same as actual servlet path. Internal name will be chosen by the developer who deploys servlet and it will be internally used in the deployment descriptor. The public URL is the one which users knows and when they request the container will find the internal name of the requested servlet and using internal name the container will find the actual path of the servlet. here the example goes. Please add the following code in the web.xml before </webpp> which is present under

{Tomcat_home_directory}\webapps\{Web_application_name}\WEB-INF folder of your web application.


<servlet>
 <servlet-name>servlet</servlet-name>
 <servlet-class>MyServlet</servlet-class>
 </servlet>

 <servlet-mapping>
 <servlet-name>servlet</servlet-name>
 <url-pattern>/callService</url-pattern>
 </servlet-mapping>

Tags & Definitions

<url-pattern> – defines the relative public URL

<servlet-name> – defines the internal name

<servlet-classs> – defines the fully qualified class name.

Yes we did it all, now restart your tomcat server, run your flex application, input email address, password, click Submit button and see the response of your servlet.

Download this application

Note : Download the application, deploy it in the webapps of your tomcat home directory. Copy the url below and paste in the address bar of your web application and run the application. http://localhost:8080/CallServlet/HttpRequest-debug/HttpRequest.html