Session management involves complex tradeoffs. The best choice depends on lots of factors, such as
- Whether you only need session state for the web interface
- What QOS you need (does performance outweigh the guaranteed survival of sessions)
- Whether users are guaranteed to accept cookies
- The volume of state you need to store
Assuming you're writing a web app, HttpSession objects are a good choice. They're well supported in most app servers and easy to use. In my experience, stateful session beans are less valuable. A lot of servers provide less robust support for SFSB replication than HttpSession replication. For example, it's hard to replicate only changed data around a cluster. Thus I wouldn't recommend SFSBs in most cases--only in the rare cases where multiple client types need session state.
Another choice in some web apps is to encode data in cookies and make the server side stateless. This only works if you have a small amount of session state, and it's best avoided unless you absolutely need the scalability a stateless web app gives you. Or hidden form fields, although again this is inelegant and relatively complex to implement.
Some more tips:
- Minimize the amount of session state you need to store, by sharing common data at application level
- Don't use large, monolithic objects in the HttpSession. Instead, use multiple smaller objects and rebind them to HttpSession only when they change. This way your app server will only need to replicate data that has been updated.
- Read your app server documentation very carefully and ensure it's configured for your desired balance of QOS and performance.
- Backing session state to a database, whether you do it yourself (yuck!) or configure the app server to persist your HttpSession objects this way, will drastically reduce performance. Don't do it unless you really need the QOS guarantee.
I discuss session management in detail in my new book, Expert One-On-One J2EE Design and Development
. You might also want to take a look at it.