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

21 Responses to this post.

  1. Posted by John Andrews on May 16, 2008 at 11:07 pm

    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. Posted by Sujit Reddy G on May 17, 2008 at 2:37 am

    Done …

  3. Posted by MrVx23 on May 20, 2008 at 2:38 pm

    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. ¿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. Posted by Sujit Reddy G on September 1, 2008 at 5:56 am

    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. Posted by Hemant Sandbhor on November 25, 2008 at 7:04 pm

    Goood Blog.
    Really helpful.

  9. Posted by Rob on March 28, 2009 at 2:05 am

    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. Posted by mohamans on April 22, 2009 at 8:48 pm

    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. Posted by mohamans on April 29, 2009 at 9:29 am

    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

  14. Posted by komark on April 30, 2009 at 12:48 am

    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

  15. Hi

    I used this sample in my code and it worked.

    Thanks Sujit Boss…

    Regards
    Rajan

  16. Posted by dl on June 9, 2009 at 5:12 pm

    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. Posted by dl on June 15, 2009 at 7:16 pm

    cool ,
    i try that ! thanks alot !

  19. Posted by daslicht on June 19, 2009 at 5:01 pm

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

  20. Posted by Ragini on June 19, 2009 at 7:48 pm

    Hi,

    how to specify the session time out for flex session ?

    thanks in advance!

Respond to this post