A simple class that stores session state.

Component Java
The road to reusable Servlet components
by Attila Szegedi
Listing 1. A simple class that stores session state.


package com.foo.myapp;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

class Session
{
  private static final String ATTNAME =
   "com.foo.myapp.Session";

  private String userName;
  private Locale locale;

  // constructors and setters omitted for
  // brevity

  String getUserName() { return username; }
  Locale getLocale() { return locale; }
  
  // On-demand per-session initializer
  static Session getInstance(
    HttpSession httpSession)
  {
    synchronized(httpSession)
    {
      Session instance = (Session)
        httpSession.getAttribute(ATTNAME);
      if(instance == null)
      {
        instance = new Session();
        httpSession.setAttribute(
          ATTNAME, instance);
      }
      return instance;
    }
  }

  static void invalidate(
    HttpSession httpSession)
  {
    synchronized(httpSession)
    {
      httpSession.removeAttribute(ATTNAME);
    }
  }
}

About the Author

Attila Szegedi is the lead developer at Scriptum, a company located in Szeged, Hungary, specializing in information retrieval and data cleansing technologies. Attila may be contacted at szegedia@freemail.hu.

Featured

Upcoming Events

AppTrends

Sign up for our newsletter.

I agree to this site's Privacy Policy.