|
|
YOUR FEEDBACK
Did you read today's front page stories & breaking news?
SYS-CON.TV |
TOP THREE LINKS YOU MUST CLICK ON Tips and Tricks
Shared Sessions Using EJBs
By: Mika Rinne
Digg This!
The Problem:
The Solution:
The Servlet API typically used with Web clients provides nice ways to manipulate the client's session and the data related to it, but doesn't offer a direct means of sharing the session data between clients (for security reasons). It's also somewhat limited to Web clients only. Enterprise Java Beans (EJBs), on the other hand, could be used to implement this quite easily, since they work with any type of Java clients. It may be a bit heavyweight, but programmatically it's quite straightforward, so let's take a closer look at it. A stateless Session EJB easily comes to mind, since it enables the client's state on the server-side. Session EJBs (or instances of them) are also sharable between client sessions by passing the reference to them (or actually into their remote interface) within the application, like a servlet. In order to pass references between sessions, the application needs to explicitly maintain a look-up table of the references for each client identified, so it knows to relate the user (along with userid) with the proper instance of a Session EJB when that already exists. However, that's pretty much what WLS does when Entity EJBs are used - or at least there is a lot of similarity in this scenario. It keeps the reference to each Entity EJB instantiated in the memory and then passes it (or the reference to the EJB's Remote Interface of it) to the client, which requests it via the bean's findByPrimaryKey method of the Home Interface. If the Entity EJB is not found since it does not yet exist, it can be created on the fly to be related with the client and its session the first time the client logs in. Therefore, Entity EJB instances are easily shared, even between clients not running in the same JVM. Note: an Entity EJB instance does not always refer to a row in the database; it can be totally virtual. But since Entity Beans are especially good at accessing persistent data, it gives us a chance to provide persistency for our sessions (and the data in them) in case of application crashes, etc. To locate the session references for clients, use of the findByPrimaryKey method is logical, since the primary key is actually the client's userid for the application. The only thing that's left for the application to do is the appropriate authentication of clients, before they can access the session data via the bean's findByPrimaryKey method.
Creating the Sample Application
1. UserSession: Class containing the user's session data in Hashtable plus some other information like the user's userId. It utilizes the Serializer class for session data persistency (see below). UserSession class can be used locally at first, and then remotely via the Entity EJB "wrapper" to be easily shared with multiple clients of many types (JSP and Java clients, etc.). 2. UserSessionSerializer: Class for session data persistency. Java serialization is used instead of JDBC in the first step to keep this as simple as possible. Later on, we can replace this with pool-oriented JDBC-based persistency for distributed larger-scale applications. There's always one file on the disk per session - even if it's shared by multiple clients -and an EJB instance accessing it. 3) EJB wrapper: For distributed UserSession objects. It's subclassed from the UserSession. As an Entity EJB, it consists of three separate classes in the sharedSessionSample.remote package (others are stored in the package "local"). 4) Sample JSP client using SessionData objects, first locally and then remotely Next, we create a package named sharedSession-Sample.local, and place two classes, the UserSession class and the UserSessionSerializer class, in it. The UserSession class has three class members (variables) and methods: Members: protected String path;Methods (the throw definitions are not shown): public void create(String userId)The class member path defines the directory where the serialized sessions are stored on the disk and loaded from. Typically, the path is the same for all sessions. The userId defines the owner of the session and is used to name the file when serialized (that is, a session of the user "John" will be serialized as a file named "John.session" onto the disk into the specified directory). The Hashtable sessionData holds the session named values. Note: we don't actually store the whole UserSession when serialized, just the sessionData member object.
Getters and Setters
The setters do not save() automatically; one has to be called explicitly by the client. However, that's implemented to the Entity EJB. One thing to note is that the UserSession is implemented in such a way that getValues() and setValues() work "by value" instead of "by reference." It's the preferred approach here, to avoid unintentional changes to the session data on JSPs (I've seen it happen many times with objects like a Hashtable). The actual code is shown in Listing 1 (the code for this article may be found online at www.sys-con.com/weblogic/sourcec.cfm. The methods create(), load(), and save() use the SessionSerializer class, which has no member variables, just static methods: public static void serialize(String path, String userId,The serialize() method is used to save (using Java serialization) the Hashtable containing the named session values onto the disk. Deserialize() is the opposite to serialize() in order to instantiate the Hashtable object from existing session values on the disk. The remove() method can delete serialized session values from the disk. Shown below are examples of the implementation of SessionSerializer's serialize() method and the UserSession's save() method to show how the use of the SessionSerializer has been implemented. The SessionSerializer's serialize method: public static void serialize(String path,The UserSession's save() method: // Note that the path needs to be set first,Next, the files are compiled into Java classes. Once we get the WLS running and these files copied into the classpath, the sample JSP page can be created to test accessing session values locally (that is, within the same JVM) as the first part of the sample. It uses the setValue() method for incrementing an integer value "i" for the user; if a user isn't specified in the HTTP request it is considered to be "JohnDoe." There's no authentication, which in real life would be needed (the standard Web app definition can be used; see Listing 2). Alternatively, the method setValues() (instead of setValue()) can be used to increment the value for "i" as shown below: int i = 0;Conversion Now that the classes for accessing the session values locally have been implemented and tested, they're prepared for remote use by both local and remote clients by being converted into an Entity EJB. That also enables easy sharing of the session data between clients, since the Entity EJB takes care of synchronization between client method calls. In addition, using bean-managed persistence (BMP) and Java serialization, we're able to serialize any named values in the Hashtable without having to worry about JDBC datatypes and so on in our EJB. However, normal rules apply when writing (updating) the same session values from two or more clients simultaneously; there's no way that the EJB could prevent overwriting of data in those cases. For that reason, make sure to add an identifier (e.g., a transaction id or timestamp from the file system, etc.) that's sent between the client and the server to indicate if the session data has been updated elsewhere (another client) when doing updates from multiple clients to the same session and its data. In order to enable the local.UserSession for remote use, three EJB classes are implemented:
All classes are placed in a package named sharedSessionSample.remote to differentiate them from the local classes (partly with same name). The UserSessionHome interface defines two methods to create new and locate existing sessions remotely: public UserSession create(String userId)Since the UserSessionBean (which we'll see in a minute) is subclassed from the local.UserSession, the remote.UserSession remote interface is used to publish the methods of the local.UserSession for remote use (the throw definitions are not shown): public Object getValue(String name)The EJB implementation class remote. User-SessionBean has only one member variable - along with those that are inherited from the local. UserSession class - and the following methods: Members: private transient EntityContext ctx;Methods (some standard EJB methods and throw definitions are not shown): public String ejbCreate(String userId)The ejbCreate() method is used to create a new session data object in case it doesn't exist yet. This object is created by calling the create() method of itself inherited from the local.User-Session class. If the creation succeeds (that is, no session exists already with the given userId), the userId is returned and the EJB is instantiated by the WLS for shared and remote use. If the session already exists, a standard DuplicateKeyException is thrown (see Listing 3). The setPath() method is used to read the serialization directory path from EJBs' properties and is implemented as follows: tryNote that in the case of clustering, which is a nice feature of WebLogic and especially typical of high load sites, the directory path should be a shared resource for all application server instances - otherwise, the clustering wouldn't work properly.
Load and Store Methods
The same load() method is used for two purposes: first, for trying to locate an existing session from the disk when doing the findByPrimary-Key(), and then for loading (deserializing) the actual data when the EJB is instantiated by the server (the ejbLoad() method). This may not be the best practice, but it works (We could have a separate find method instead, but to limit the size of the code we omit that). The ejbStore() method is called automatically by the server when any setter of the EJB is called. Therefore, there's no need for an explicit save() method in the EJB. We could easily add it for optimization reasons later on, but it's hardly needed here. Thus, the ejbStore() method is as follows: tryFinally, the ejbRemove() method, which can be used to delete existing session data: tryNow that the EJB is ready, it's time to modify the JSP for using the EJB instead of the local class. In Listing 5, the UserSession is accessed remotely to do basically the same increment as in Listing 2, but now it enables the client (a standalone Java application, for example) to run in a separate JVM from the server. In order to set more than one value at a time, the setValues() method can be used, as in this example of incrementing: int i = 0;For optimization, the JNDI lookup for the EJB could be done only once and stored in the WebLogic Server's memory with application scope (see Listing 6). In addition, we could also cache the UserSession object itself to the user's HTTP session once found, in order to avoid subsequent findByPrimaryKey() calls in case of JSP. Of course, for Java clients like applets, the caching isn't needed (used as a local object). The code for caching is shown in Listing 7.
BEA WEBLOGIC LATEST STORIES
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
|
SYS-CON FEATURED WHITEPAPERS MOST READ THIS WEEK BREAKING NEWS FROM THE WIRES
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||