Session data management in Flex Remoting

If you are using Flex Remoting to communicate with Java classes on the server, you might want to maintain instance of an object across a user session. For example you might want to store the User object after successful authentication of a user. BlazeDS provides class named FlexContext.

Please visit the BlazeDS Developer guide at this URL for more details on FlexContext class and session data management. BlazeDS Developer Guide

Updated: Free AIR based Tool to generate Flex code for consuming/exposing Java classes as BlazeDS Remoting services. Visit this URL for more details

I created a simple Java class which will add objects to session. It will also retrieve objects from session and modify them. I access this Java class from a Flex application to get the data which is stored in user session. In this sample we will be creating one Java class and one .mxml file.

Pre-requisite: Knowledge on how to invoke Java methods from Flex applications and also have BlazeDS set up on your server. If you have not done this, please visit this URL for details on how to access Java methods from Flex applications. Invoking Java methods from Flex applications

Let’s move into details. First create a Java class as shown below.

Download this file from this URL:

In the constructor I am checking if object already exists in the session and add objects if necessary. We have two objects in the session. One is userName which is object of type java.lang.String and myCounter which is object of type java.lang.Integer and is used to store a counter. We will provide method to increment this counter.

public MySessionHandler()


mySession= FlexContext.getFlexSession();

if(mySession.getAttribute(“myCounter”) == null)


mySession.setAttribute(“myCounter”, new Integer(1));


if(mySession.getAttribute(“userName”) == null)


mySession.setAttribute(“userName”, “Sujit Reddy G”);



In this method we are incrementing the value of the object stored in the session.

public void increaseCounter()


Integer i = (Integer) mySession.getAttribute(“myCounter”);

i = i + 1;

mySession.setAttribute(“myCounter”, i);


You can find more methods in Java file attached. Download the file and place the compiled file into WEB-INF/classes folder of the web application where your BlazeDS is present. You should add flex-messaging-core.jar to your project build path in Eclipse to compile this class.

You should add a destination to your remoting-config.xml. I have added the following under the service tag in my remoting-config.xml.

<destination id=”MySessionHandler” channels=”my-amf”>




<adapter ref=”java-object”/>



Download this file from this URL: SessionSample.mxml

In this Flex application we have three buttons which will invoke methods on the Java class created above to get the results. There are three methods which we will invoke.

getUserName() – this will return the user name stored in the session

getCounter() – this will return the value of the counter

increaseCounter() – this will increment the counter value

You have to map your Flex application to the web application with BlazeDS as described in the pre-requisite for this blog.

That is all you need to do. It’s that easy to manage session data while using Flex Remoting. 🙂

44 Responses to Session data management in Flex Remoting

  1. John Andrews says:

    It would be great if you could list the resources you used to write this article. Some sentences are directly taken from BlazeDS/LCDS documentation.

  2. Sujit Reddy G says:

    Done …

  3. MrVx23 says:

    Hi, this may be due to JBoss setup, but when I try to run this example, I get a server processing error: java.lang.NoClassDefFoundError : flex/messaging/FlexContext. Clearly it cant find the jars in my blazeds.war/WEB-INF/lib directory. I’ve got the server working OK with EJBs and whatnot, so any ideas why it cant locate a library local to the blazeds.war ? Should it, even, or does it need some indication in some .xml files?

  4. […] G. is a fantastic blogger with quite a few good articles on data services. I found his blog while search of information on custom messaging […]

  5. […] I carry session across remote method calls? Great that I have found out how to handle it via this article. In short, you can access Session from your Java object […]

  6. Carlos says:

    ¿Do you know if I can set any variable to avoid the auto-creation of a session when calling Remote Objects?

    For my application, only 1 object should create the session after authentication, and all other calls to the server should ask for a valid session (without the possibility of creating one) and deny the service if none or expired.

    I want something like in JSPs, where I can set the Session tag to false and manually get the session from Request.getSession(false)

  7. Sujit Reddy G says:

    Hi Carlos,

    I am not aware of any such configuration. From top of my mind you can achieve this by adding a object in the session and check if that object is available and then reject the user’s request. You can also set a boolean in the session to check if the user logged in …

    I will try to check if there is any such configuration available..

    Hope this helps. 🙂

  8. Hemant Sandbhor says:

    Goood Blog.
    Really helpful.

  9. Rob says:

    How do we perform auto logout when the session expires or when the channel is disconnected. I had implemented logout dispatch event in the channel disconnected handler, but that does not get initiated when the server does not get messaging requests from a particular client\session

  10. Hi Rob,

    I did not understand what you are trying to achieve. Can you please explain?

  11. mohamans says:

    Hi Sujit,
    I have a simillar question to Rob’s. I want to implement something like disconnect or close session. That is, when the client 1 opens a session, e.g., the sessionId (FlexContext.getFlexSession().getId() — thanx for tip) is stored somewhere in a list (application context or flat file or database), and when the client 2 opens a session, the sessionId is stored also and so on. Now the question is:

    – how I can get (in Java side) the sessionId of the closed session (by expire or e.g. closing the browser)?

  12. Hi Mohamans,

    Why don’t you try adding a session listener.

    Hope this helps.

  13. mohamans says:

    Thanks Sujit,
    I have already used it, but it does not work.

    in Java Service when I first connect to a database server, I used:

    FlexSession.addSessionCreatedListener(new MyFlexSessionListener());

    this is my listner implementation:

    public class MyFlexSessionListener implements FlexSessionListener {

    public void sessionCreated(FlexSession session) {
    System.out.println(“FlexSession created: ” + session.getId());
    // Add the FlexSession destroyed listener.

    public void sessionDestroyed(FlexSession session) {
    System.out.println(“FlexSession destroyed: ” + session.getId());

    FlexContext.getFlexSession().setAttribute(“dbconnection”, null);


    and this does not work. I have also tried to set “invalidate-session-on-disconnect” and that makes no changes.

    can you please tell me what is wrong?


  14. komark says:

    Hi Sujit,
    The problem is most of the time when session expires, we will redirect to home page most of the time(jsp/servlet web app). This page will then handled by the browser, but when comes to SWF file the handler is Flash Plugin, this by default will just ignore unless you explicitely catch response. So one needs to Reload the application in order to get a browser session with server. Is there a way to unload flex application and perform web based authentication and reload flex app to get a fresh session? Please suggest.


  15. Rajan says:


    I used this sample in my code and it worked.

    Thanks Sujit Boss…


  16. dl says:

    How do I read all connected users ? How do I get all running sessions ?

  17. Hi dl,

    you can add session listeners and keep track of them

    Hope this helps.

  18. dl says:

    cool ,
    i try that ! thanks alot !

  19. daslicht says:

    Hm, I dont get it , how could I use that to get all subscribed users ?

  20. Ragini says:


    how to specify the session time out for flex session ?

    thanks in advance!

  21. Hi daslicht,

    subscribed users are the users subscribed to a messaging destination. If you are not using messaging and want to maintain a list of users logged in to your server, you will have to register a session listener and maintain list of users when the sessions are created.

    Hope this helps.

  22. Hi Mohamans,

    Can you please check and make sure the call to FlexSession.addSessionCreatedListener(new MyFlexSessionListener()); is made. I am planning to write a blog post on how to do this, but honestly got stuck with a lot of deadlines 😦

    Hope this helps 🙂

  23. Hi Ragini,

    Please try this

    private FlexSession session;
    session = FlexContext.getFlexSession();

    Hope this helps.

  24. Aina says:

    hi all

    I’ve just load-tested the Spring Blaze DS sample app on springsource website. I use JMeter as a load-testing tool.
    JMeter has an internal proxy that lets you record the http session by just starting the proxy and interacting with your web app as you would in normal situations. And once you have the scenario, you can tell JMeter to play it back on your web app so as to generate load on your server.
    Everything is okay when dealing with the Spring blaze DS sample App.

    But I’ve tried to load test another flex app. Actually, JMeter can record the scenario but when playing it back : i have 100% errors on some of my swf 😥

    Do you know whether there are some constraints to manage when dealing with Flex apps ? I mean something with the SESSION for example (session ids etc)…

    thanks in advance for your help …

  25. Hi Aina,

    I am sorry I don’t have much knowledge on this. I will see if I can understand or get some one to help you out. 🙂

  26. Gauranga says:


    Excellent post, helped alot!


  27. dev says:


    great sample..

    Im not able to compile java file..showing comiple time error: package flex.messaging does not exist..
    can you please guide me on this..


  28. vasu says:

    Hi Sujit,

    Am experimenting my old java app with blazeDS,
    in that am using session like this


    to get the session parameters am using getAttribute(“loginUser”);

    but now i want to LogOut from session..
    now am in confusion about how to destroy session
    should i use follows blindly or else is there any standard way to close session.

    FlexContext.getFlexSession().setAttribute(“loginUser”, null);

    Thankyou very much in advanced to this reply… 😉

  29. Hi Vasu,

    Please try the following


    Please find more details on the FlexSession at the URL below

    Hope this helps.

  30. David says:

    I integrate my flex app in my jsf-icefaces app (or better in a jspx site) and i want to connect to the current jsf session to connect to the session entity manager of the jsf app. i already connect to a bean, but there i didnt get the current jsf session with FacesContext…getSession()… like i get the current flex session with FlexContext.getFlexSession(). this is because flex inject the bean and it’s not the same current instance that jsf inject, i think. i hope there is any chance to communicate throw the sessions..? do anybody know something about that?!

    sorry for my english 😉

  31. Eduardo says:

    hola, estoy experimentando el uso de este ejemplo, yo tengo una aplicacion que recibe los parametros mediante un servlet, estos parametros se los envio directamente al metodo MySessionHandler, pero al ejecutar el servlet me marca un error de tipo nullpointer, me podrias ayudar al respecto Sujit, gracias. PD una disculpa por el ingles

  32. Aubweb says:

    Hi Sujit,

    Maybe you can help to solve this issue :

    [RPC Fault faultString=”Detected duplicate HTTP-based FlexSessions, generally due to the remote host disabling session cookies. Session cookies must be enabled to manage the client connection correctly.” faultCode=”Server.Processing.DuplicateSessionDetected” faultDetail=”null”]

    I don’t know where it comes from and how to avoid this error.
    (i am using flex with coldfusion)

  33. Jorge Rodriguez says:

    Hi everyone;

    I have a question, if I need to get Session set by JSP(request.getSession().setAttribute(name, value)) What should I do?

    Best Regards

  34. Sarath says:

    Hi Everyone,
    Who is creating the FlexSession in blazeds. Who is responsible for creating the session in blazeds. I used addSessionCreatedListener but it is not calling the sessionCreated method in my listnere.. 😦 ?

  35. Rajkumar says:

    Hi All,

    How can i invalidate flex session if user click on IE refresh or back button.

  36. Manzoor says:

    Hi Sujith,

    I have an application client which connects to server using blazeds. I have implemented session in this system as you explained. But i want one another feature that when the client appl is inactive ie if there is no request from the client for some time session must timeout. If user makes another request then server could return appropriate tag( eg: a boolean value) indicating that session expired and based on that client could redirect to login page.
    I have given mySession.setTimeoutPeriod(1);
    But it doesn’t work. Session doesnot expire after the specified time. I have set


    in web.xml It also failed.

    What could be the reason


  37. avi says:


    is it possible to define filter for flex application. so that every request for server goes through this filter and i can validate if user is logged in there itself instead of validating in each java class and redirect to login page if session is not valid


  38. Tom says:

    Hi Sujit,
    I am using Flex3 and for communicating with Java i am using Blazeds & RemoteObject.
    in remoting-config.xml i added destination like this->


    Every thing was working fine but when i call some methods for example adding some data in my “” which will take more time to respond for example more than 1 hour or more, in Flex side after 30 mins(not accurate) in the fault handler of my remoteobject I am getting error like below, but in server side still data adding is happening, can you please help me on this.
    If i have less data the same is working fine ->
    Error Details ****************************
    info = (@2015487)
    bubbles = false
    cancelable = true
    currentTarget = null
    eventPhase = 2
    fault = mx.rpc.Fault (@2015487)
    [inherited] =
    content = Object (@22f6a59)
    faultCode = “Channel.Call.Failed”
    faultDetail = “NetConnection.Call.Failed: HTTP: Failed”
    faultString = “error”
    rootCause = Object (@3d0a484)
    headers = null
    message = mx.messaging.messages.ErrorMessage (@843aa03)
    [inherited] =
    extendedData = null
    faultCode = “Channel.Call.Failed”
    faultDetail = “NetConnection.Call.Failed: HTTP: Failed”
    faultString = “error”
    rootCause = Object (@8d0a581)
    code = “NetConnection.Call.Failed”
    description = “HTTP: Failed”
    details = “;jsessionid=k13A45DB2765FC7AE0D771200254310T”
    level = “error”
    messageId = “544FDC7C-9D29-7635-D439-5B154EB51E0B”
    statusCode = 0
    target = null
    token = mx.rpc.AsyncToken (@8073a81)
    [inherited] =
    message = mx.messaging.messages.RemotingMessage (@819f2c9)
    [inherited] =
    operation = “addMyData”
    source = null
    responders = Array (@7c41719)
    result = null
    type = “fault”

  39. Tom says:

    Hi Sujit,
    I am using Flex3 and for comunicating with java using Blazeds & remoteobject. In remoting-config.xml i added my destination for example like this->


    When I call a method which will add data and if it take more response time for example more than 1 hr, in flex side in the fault handler of my remoteobject i am getting error which i given below, if data that i need to add is very less its working fine without any isssue. Can u please help me on this.
    Error Details:
    info = (@1276351)
    bubbles = false
    cancelable = true
    currentTarget = null
    eventPhase = 2
    fault = mx.rpc.Fault (@8076041)
    [inherited] =
    content = Object (@82f6a91)
    faultCode = “Channel.Call.Failed”
    faultDetail = “NetConnection.Call.Failed: HTTP: Failed”
    faultString = “error”
    rootCause = Object (@8d0a581)
    headers = null
    message = mx.messaging.messages.ErrorMessage (@8d3aa01)
    [inherited] =
    extendedData = null
    faultCode = “Channel.Call.Failed”
    faultDetail = “NetConnection.Call.Failed: HTTP: Failed”
    faultString = “error”
    rootCause = Object (@8d0a581)
    code = “NetConnection.Call.Failed”
    description = “HTTP: Failed”
    details = “;jsessionid=A53A45DB2765FC7HJ0D771200226310Z”
    level = “error”
    messageId = “544FDC7C-9D29-7635-D439-5B154EB51E0B”
    statusCode = 0
    target = null
    token = mx.rpc.AsyncToken (@8073a81)
    [inherited] =
    message = mx.messaging.messages.RemotingMessage (@819f2c9)
    [inherited] =
    operation = “addMyData”
    source = null
    responders = Array (@7c41747)
    result = null
    type = “fault”

  40. Hi Tom,

    How big is your data?

  41. Tom says:

    Its not actually due to data, i have some data near to 2000 records, but in server based on each record some background extra work is there, I mean its not just adding to a Database, we need to ping to some other machine to see some status etc.

  42. trader says:

    I am unable to download

    Could you please help me out?

    I really appreciate your help.


  43. Hi Trader,

    Looks like there is some problem with server. Please try downloading from here

    Thank you.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: