Thursday, May 7, 2009

Accessing HTTP Request/Header parameter in Flex

I hope this blog will help flex newbie to understand the ways to pass/access http request/header parameter in flex application.

To access http request/header, following approaches can be used -

  1. Load you flex application in a jsp page and pass the http request/header details through flashvars to flex application. I will discuss this further with code and limitation.
  2. Write a httpservlet and call the servlet from flex application using httpservice and get the response as e4x xml for required parameters.
  3. Instantiate servlet using flex httpservice and store the request/header parameter in it and access them using remoting service via java objects.

These approaches can be used if siteminder token other http request/header information need to be passed to flex application.

Approaches

A. Passing variable from JSP to Flex, variable can be user defined, system or http request/header variable.

Step 1. Change the html in which flex is embedded to jsp. Nothing required just save it from index.html to index.jsp its done.

Step 2. Define variable in index.jsp in this case we are trying to pass user-agent value to flex app.
<% String parameterA = (String)request.getHeader("user-agent");%>

Step3. Search "if (hasRequestedVersion)" in index.jsp , it will look something like this
else if (hasRequestedVersion) {
// if we've detected an acceptable version
// embed the Flash Content SWF when all tests are passed
AC_FL_RunContent(
"src", "AccessParameter",
"width", "100%",
"height", "100%",
"align", "middle",
"id", "AccessParameter",
"quality", "high",
"bgcolor", "#869ca7",
"name", "AccessParameter",
"allowScriptAccess","sameDomain",
"type", "application/x-shockwave-flash",
"pluginspage", "http://www.adobe.com/go/getflashplayer"
);


Add flashVars line for parameterA like this
"FlashVars",'parameterA=<%parameterA%>',

incase you want to pass html and pass value in it.
"FlashVars",'parameterA=test123',

Step4. Now we need to access the parameterA value in flex application. It can be either accessed directly at application.mxml file or in actionscript sub classes

To access parameterA values in application mxml, write a method accessJspVariable call it in completionComplete tag of application mxml or in case you have init(), call this method from init() method.

function accessJspVariable():void{
var parameterA=Application.application.parameters.parameterA
Alert.show("Variable passed by JSP :"+parameterA);
}

Incase you want to access this variable direclty in some actionscript class. First
import mx.core.application;

var parameterA=Application.application.parameters.parameterA;

Source code is upload. HTML file loaded instead of JSP as JSP would require server to run it.