AJAX Tutorial for Java Programmers

Saving Your Own Data in the Session

Earlier we learned about the session, and how to use it for form elements.

The session is a useful concept, and in addition to form elements, it can also be helpful to save your own data for a user.

The Jaxcent "session" matches the "session" of a Java Application Server if Jaxcent is running in a Java Application Server. Therefore if you have a legacy web application using a Java Application Server, you can use the session from both Jaxcent pages and the Application Server servlets/JSPs, and they can co-operate.

In general, however, it is not guaranteed that you are running inside a Java Application Server. Jaxcent could be directly connected to an IIS or Apache web server, or there may be some other configuration.

You will still have some kind of a session available, but it may not be an Application Server's session.

Therefore, to save any data for your own use, it's best to store it in the java.util.Map that Jaxcent makes available. If you enable AutoSessionData this Map will be available to you. The Map just stores the values of all form field using names/ids as keys (keys are lowercased, retrieval is case independent) in this map. So as long as you don't collide with these names, you can store your own values in the same Map, and it will be available to you for the duration of the user's session.

The Map is available by calling getAllSessionData( false ); from any page with AutoSessionData enabled. If the parameter is true, the session will first be updated with any data on the current page.

Exercise:  Earlier we made a small shopping-cart type application. Modify the MyPage.java as follows:

  1. Add AutoSessionData in the mapping for MyPage.html.
  2. Add a "bookList" field of class Vector (can't be ArrayList without adding synchronization, therefore Vector is convenient.)
  3. In the constructor, retrieve the data Map (parameter must be false, there is no page connected in the constructor) and get the element bookList from this map at key "MyPage.shoppingCart". If the element is null, create the Vector bookList, and store it at that key. If the element is not null, it must be the Vector you have saved earlier. Populate the table from it.
  4. As you save data in the table, also store the book names in the "bookList" Vector.
  5. Now everytime you visit the page again (without having timed out the session), you should see the shopping cart populated from any earlier choices.
  6. You will notice a slight problem -- the AutoSessionData will keep the previous SELECT selection highlighted even though in this case we don't want this data to be saved! This can be fixed by putting the mySelect.setSelectedIndex( -1 ); in an onLoad override instead of the constructor, so this can be reset at page load.
     
Next Step: Dragging and Dropping