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 http://sujitreddyg.wordpress.com/2009/05/07/blazemonster/

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.

com.adobe.services.MySessionHandler.java

Download this file from this URL: MySessionHandler.java

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”>

<properties>

<source>com.adobe.services.MySessionHandler</source>

</properties>

<adapter ref=”java-object”/>

</destination>

SessionSample.mxml

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. :)

28 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. FlexLive.net » Flex Developer Update - May 20, 2008 Says:

    [...] 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. Solution Hacker - Flex Remoting and Session Management Says:

    [...] 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. Flex and Cairngrom Architecture « Vengatc techology logs Says:

    [...] http://sujitreddyg.wordpress.com/2008/05/16/session-data-management-in-flex-remoting/ [...]

  9. Hemant Sandbhor Says:

    Goood Blog.
    Really helpful.

  10. 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

  11. Sujit Reddy G Says:

    Hi Rob,

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

  12. 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)?
    -

  13. Sujit Reddy G Says:

    Hi Mohamans,

    Why don’t you try adding a session listener.

    Hope this helps.

  14. 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.
    session.addSessionDestroyedListener(this);
    }

    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?

    Thnaks
    Mohamans

  15. 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.

    Thanks
    komark

  16. Rajan Says:

    Hi

    I used this sample in my code and it worked.

    Thanks Sujit Boss…

    Regards
    Rajan

  17. dl Says:

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

  18. Sujit Reddy G Says:

    Hi dl,

    you can add session listeners and keep track of them

    Hope this helps.

  19. dl Says:

    cool ,
    i try that ! thanks alot !

  20. daslicht Says:

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

  21. Ragini Says:

    Hi,

    how to specify the session time out for flex session ?

    thanks in advance!

  22. Sujit Reddy G Says:

    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.

  23. Sujit Reddy G Says:

    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 :)

  24. Sujit Reddy G Says:

    Hi Ragini,

    Please try this

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

    Hope this helps.

  25. 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 …

  26. Sujit Reddy G Says:

    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. :)

  27. Gauranga Says:

    Hi,

    Excellent post, helped alot!

    Thanks.

  28. dev Says:

    Hi,

    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..

    thanks

Leave a Reply