How to get URL query-string variables within Flex application
On flexcoders, someone asked, how to get the URL parameters in a Flex 2.0 application? By URL parameter, I mean the query-string variables, as shown below.
http://yourserver/yourapp.swf?name=Joe&age=22 or http://yourserver/yourapp.mxml?name=Joe&age=22 (requires server in place)
name and age are the query-string variables.
You can get the values of the params using from mx.core.Application.application.parameters object, which contains the name-value pairs (hash-map).
For example, mx.core.Application.application.parameters.name would return “Joe”, considering above example URL.
You can find more information about this in livedocs: http://livedocs.macromedia.com/flex/20beta1/docs/00001300.html
Then someone asked, what if your swf is embedded in custom html wrapper, how to get the query-string params inside swf? Solution is to use ExternalInterface class in Macromedia Flash Player 8(onwards) to invoke some JavaScript functions and extract the value in ActionScript.
I wrote a quick-and-dirty class in ActionScript 3, which would get the values of params from URL query-string for you. You don’t need any extra JavaScript code in HTML. The same logic can be used for any an ActionScript 2.0 running Macromedia Flash Player 8.
QueryString class has following properties:-
parameters– an Object which contains the name-value pairs from query-stringqueryString- String, this contains the entire query-string (url-encoded) name-value pairs.url- String, this returns the complete URL of the wrapper page with query-string.



Abdul,
Thanks this is a great site, I’ve learned a lot already. I thought your QueryString class was very intuitive and easy to use. I wanted to let you know I actually liked it so much I ported it back to as2. And I figured I’d share that as well, so it’s at my blog post here, Get Current URL and Query String Parameters to Flash. Just to let you know!
Thanks again for the class,
Evan @ Circlecube.com
Hi..i am trying to do fileuplaod from flex to java servlet..problem is request is not coming to servlet..If I use jsp instead of servlet then request is coming to jsp..am not sure what’s wrong with srvlet approach..any help woudl be appreciated
here is my code:
here is my servlet
……………….
package com.boa.flex.servlet;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author nbkzk5e
*
*/
public class UploadFileServlet extends HttpServlet
{
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
private static final Log log = LogFactory.getLog(UploadFileServlet.class);
//@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
doPost(req,resp);
}
//@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
log.info(”am in servlet”);
log.info(”author”+req);
File disk = null;
FileItem item = null;
FileItemFactory factory = new DiskFileItemFactory();
Iterator iter = null;
List items = null;
ServletFileUpload upload = new ServletFileUpload( factory );
ServletOutputStream out = null;
try
{
// Parse the incoming HTTP request
// Commons takes over incoming request at this point
// Get an iterator for all the data that was sent
// TODO: Leverage generics
log.info(”am in servlet”);
items = upload.parseRequest( req );
iter = items.iterator();
// Set a response content type
res.setContentType( “text/xml” );
// Setup the output stream for the return XML data
out = res.getOutputStream();
out.println( “” );
// Iterate through the incoming request data
while( iter.hasNext() )
{
// Get the current item in the iteration
item = ( FileItem )iter.next();
// If the current item is an HTML form field
if( item.isFormField() )
{
// Return an XML node with the field name and value
out.println( “” );
// If the current item is file data
} else {
// Specify where on disk to write the file
// Using a servlet init param to specify location on disk
// Write the file data to disk
// TODO: Place restrictions on upload data
disk = new File( “C:\\”+item.getName() );
log.info(”am after disk”);
item.write( disk );
// Return an XML node with the file name and size (in bytes)
out.println( “” );
}
}
// Close off the response XML data and stream
out.println( “” );
out.close();
// Rudimentary handling of any exceptions
// TODO: Something useful if an error occurs
} catch( FileUploadException fue ) {
fue.printStackTrace();
} catch( IOException ioe ) {
log.info(”io error”);
ioe.printStackTrace();
} catch( Exception e ) {
e.printStackTrace();
}
}
}
here is web.xml
……………..
XFireServlet
org.codehaus.xfire.transport.http.XFireConfigurableServlet
XFireServlet
/servlet/XFireServlet/*
XFireServlet
/services/*
FileServlet
com.boa.flex.servlet.UploadFileServlet
FileServlet
/action/*
@Evans: Thanks. Please feel free to use this code in whatever way you want to.
@Baji: I can’t see flex code, please post it again enclosed by <pre>yourcode</pre>
@Steve: I think you aren’t running the code inside a webserver. Try running it on localhost, or place it on your webserver (or install LAMP/WAMP/MAMP for a quick Apache/Mysql environment on you local machine)
Great job Abdul!
Hi,
With all those comments I still can’t get it running…
Here’s my situation:
Dynamically generated page by Typo3 CMS.
On this page I have a little Flex application. And this application should detect the language parameter from the URL, wich is L.
The url looks like this : http://www.domain.com/index.php?id=1125&L=1
I’ve tried all your solutions… nothing!
When I launch the flex app from Flexbuilder, I can see that qs.url contains the url. Good. But queryString remains desperatly empty…
And when I deploy the flex app to the website, then qs.url also remains empty…??
What did I forgot?? I’m really desperate…
Hi,
With all those comments I still can’t get it running…
Here’s my situation:
Dynamically generated page by Typo3 CMS.
On this page I have a little Flex application. And this application should detect the language parameter from the URL, wich is L.
The url looks like this : http://www.domain.com/index.php?id=1125&L=1
I’ve tried all your solutions… nothing!
When I launch the flex app from Flexbuilder, I can see that qs.url contains the url. Good. But queryString remains desperatly empty…
And when I deploy the flex app to the website, then qs.url also remains empty…??
What did I forgot?? I’m really desperate…
Nice joob ;D
Hi, now what is the equivalent of Application.application.url in flash as3 ?? how to get the url in as3?? pls help..
Thanks, this article very good, I try successfull, one more thanks.
I doubt anybody will read this far, but it is much easier to use URLUtil.stringToObject to decode the query string. And it can handle decoding the parameters.
Hi Abdul,
I have been a web application developer using JSP and servlets etc. Now i am entering into flex development. Can you point me to some resource that can help me make the transition (Specfically aimed at Java web developers).
Thanks in advance,
Varun
Hi Mr. Abdul Qabiz
Can you advice me, what is the Variable or AS set for in the SWF? for both the Name & Hometown according to your SOURCE FILE. Can you show me the FLA?
hi Abdul,
when i am passing values to html it is working fine for both mozila and Internet Explorer.
I have used your class it is awesome and realy greate work.
But still i have found some problem with this class
and when i am passing values directly to swf like
http://localhost/myswf.swf?myname=faisal
in mozila it is working perfect but not working for internet explorer.
is it possible to pass values to swf in internet explorer or this is limitation of class or am i missing something ?
Please Help !
Hope you will reply.
Thanks
This helped me, thank you soo much
I can’t believe how long I had to search for this, it’s exactly what I needed yet no body on any of the forums could help me. I knew the solution was there but it’s a matter of knowing how to access the variable name.
Thanks so much,
Nice Article Adul
@vajahat: Glad to know, you found it useful. It’s very old one and I believe, it can updated to use better technique.
Thank you very much, I started to use your class right away.
@olga:
Glad to know, it helped you.
-abdul
Hi Abdul,
That’s great !
Here is a very interesting use of your code:
I have two Applications. MyAppWidget is a small swf used to navigate to different main applications on different servers.
In MyAppWidget:
var url:String = “”
url += navigateEvent.applicationBaseURL;
var request:URLRequest = new URLRequest(url);
var variables:URLVariables = new URLVariables();
variables.email = _modelLocator.loginAttempt.username;
variables.pwd = _modelLocator.loginAttempt.password;
request.data = variables;
request.method = URLRequestMethod.GET;
try {
navigateToURL(request);
…
Im MyMainApp:
I use your wrapper and it work great ! However, as you can see my parameters are email and encrypted pwd over https, so I would like to use the URLRequestMethod.POST (not GET) to hide it (it’s best practice too) and in this case the script doesn’t work anymore…
Any suggestion ?
By the way, I have a recommendation: It will be great to create a js that can simply be include in the standard flex wrapper (html) and “push” flashvar on demand. I’m so disappointed that it’s not out of the Flex 3 box ! maybe in Flex 4 ? My understanding is that BrowserManager can only read fragment (everything after # character by using browserManager.fragment) and not parameters (from GET or POST function in HTML)
Simon