Search code examples
javadesign-patternscontrollerhttpsession

Design pattern for managing information that is set/modified/used in http sessions by different controllers?


What's the common approach (or design pattern) for this "problem" :

  1. I have a lot of controllers in a web application (struts actions in JAVA to be precise).
  2. Some controllers sets variables in the user's session.
  3. Some controllers use those variables, remove them, modify them, etc...

It's messy because it's hard to know who set what, in what condition, where it changes...

Should I use the Mediator pattern : http://en.wikipedia.org/wiki/Mediator_pattern

Or the Facade pattern like this (example in c#) : http://foxsys.blogspot.ca/2007/01/session-facade-aspnet-c.html

Or something else?


Example of the workflow of a variable and how it can be messy :

  1. The user choses a preferred product. The ChooseProductController sets the id of the preferred product in session

  2. The user creates an account : The CreateAccountController checks if a preferred product is in session. If it's the case, it creates the account in DB with this id

  3. The user is logged in. The LoginController checks if a preferred product is in session. If it's different from the one in DB when the account was created, the view needs to display a message to ask the use to choose the preferred product.


Solution

  • First advice: use the session as seldomly as possible. Try to only use it for things that have a lifetime identical to the lifetime of the session, and that can't be retrieved from the database easily or fast enough.

    Second advice: don't use the session directly. Encapsulate the access to the session in one or a few dedicated class(es) (like you would do for a database, except the session is an in-memory database). Instead of doing

    Product preferredProduct = (Product) session.getAttribute("preferredProduct");
    

    , do something like

    SessionStore.getInstance(session).getPreferredProduct();
    

    This is more readable, much less error-prone, and allows finding easily in all the codebase where the preferred product is get or set.