Sun ONE logo     Previous      Contents      Index      Next     
Sun ONE Application Server 7, Update 1 Developer's Guide to Web Applications



Creating and Managing User Sessions

This module describes how to create and manage a session that allows users and transaction information to persist between interactions.

This module contains the following sections:

Introducing Sessions

The term user session refers to a series of user application interactions that are tracked by the server. Sessions are used for maintaining user specific state, including persistent objects (like handles to EJB components or database result sets) and authenticated user identities, among many interactions. For example, a session could be used to track a validated user login followed by a series of directed activities for a particular user.

The session itself resides in the server. For each request, the client transmits the session ID in a cookie or, if the browser does not allow cookies, the server automatically writes the session ID into the URL.

The Sun ONE Application Server supports the servlet standard session interface, called HttpSession, for all session activities. This interface enables you to write portable, secure servlets.

Sessions and Cookies

A cookie is a small collection of information that can be transmitted to a calling browser, which retrieves it on each subsequent call from the browser so that the server can recognize calls from the same client. A cookie is returned with each call to the site that created it, unless it expires.

Sessions are maintained automatically by a session cookie that is sent to the client when the session is first created. The session cookie contains the session ID, which identifies the client to the browser on each successive interaction. If a client does not support or allow cookies, the server rewrites the URLs where the session ID appears in the URLs from that client.

You can configure whether and how sessions use cookies. See the session-properties and cookie-properties elements in the sun-web.xml file, described in "Assembling and Deploying Web Modules."

Sessions and URL Rewriting

There are two situations in which the Sun ONE Application Server plugin performs implicit URL rewriting:

  • When a response comes back from the Sun ONE Application Server; if implicit URL rewriting has been chosen, the plugin rewrites the URLs in the response before passing the response on to the client.
  • When the request given by a client need not be sent to the Sun ONE Application Server and can be served on the web server side. Such requests may occur in the middle of a session and the response may need to be rewritten.

You can configure whether sessions use URL rewriting. See the session-properties element in the sun-web.xml file, described in "Assembling and Deploying Web Modules."

Sessions and Security

The Sun ONE Application Server security model is based on an authenticated user session. Once a session has been created the application user is authenticated (if authentication is used) and logged in to the session. Each interaction step from the servlet that receives an EJB request does two things: generates content for a JSP to format the output, and checks that the user is properly authenticated.

Additionally, you can specify that a session cookie is only passed on a secured connection (that is, HTTPS), so the session can only remain active on a secure channel.

For more information about security, see "Securing Web Applications."

How to Use Sessions

To use a session, first create a session using the HttpServletRequest method getSession(). Once the session is established, examine and set its properties using the provided methods. If desired, set the session to time out after being inactive for a defined time period or invalidate it manually. You can also bind objects to the session which store them for use by other components.

Creating or Accessing a Session

To create a new session or to gain access to an existing session, use the HttpServletRequest method getSession(), as shown in the following example:

HttpSession mySession = request.getSession();

getSession() returns the valid session object associated with the request, identified in the session cookie which is encapsulated in the request object. Calling the method with no arguments, creates a session if one does not already exist which is associated with the request. Additionally, calling the method with a Boolean argument creates a session only if the argument is true.

The following example shows the doPost() method from a servlet which only performs the servlet's main functions, if the session is present. Note that, the false parameter to getSession() prevents the servlet from creating a new session if one does not already exist:

public void doPost (HttpServletRequest req,
                  HttpServletResponse res)
            throws ServletException, IOException
{
   if ( HttpSession session = req.getSession(false) )
   {
      // session retrieved, continue with servlet operations
   }
   else
      // no session, return an error page

   }
}



Note

The getSession() method should be called before anything is written to the response stream. Otherwise the SetCookie string is placed in the HTTP response body instead of the HTTP header.



For more information about getSession(), see the Java Servlet Specification v2.3.

Examining Session Properties

Once a session ID has been established, use the methods in the HttpSession interface to examine session properties, and methods in the HttpServletRequest interface to examine request properties that relate to the session.

The following table shows the methods to examine session properties. The left column lists HttpSession methods, and the right column lists descriptions of these methods.

   HttpSession Methods

HttpSession method

Description

getCreationTime()

 

Returns the session time in milliseconds since January 1, 1970, 00:00:00 GMT.

 

getId()

 

Returns the assigned session identifier. An HTTP session's identifier is a unique string which is created and maintained by the server.

 

getLastAccessedTime()

 

Returns the last time the client sent a request carrying the assigned session identifier (or -1 if its a new session) in milliseconds since January 1, 1970, 00:00:00 GMT.

 

isNew()

 

Returns a Boolean value indicating if the session is new. Its a new session, if the server has created it and the client has not sent a request to it. This means, the client has not acknowledged or joined the session and may not return the correct session identification information when making its next request.

 

For example:

String mySessionID = mySession.getId();
if ( mySession.isNew() ) {
   log.println(currentDate);
   log.println("client has not yet joined session " + mySessionID);
}

The following table shows the methods to examine servlet request properties. The left column lists HttpServletRequest methods, and the right column lists descriptions of these methods.

   HttpServletRequest Methods  

HttpServletRequest Methods

Description

getRemoteUser()

 

Gets the requesting user name (HTTP authentication can provide the information). Returns null if the request has no user name information.

 

getRequestedSessionId()

 

Returns the session ID specified with the request. This may differ from the session ID in the current session if the session ID given by the client is invalid and a new session was created. Returns null if the request does not have a session associated with it.

 

isRequestedSessionIdValid()

 

Checks if the request is associated to a currently valid session. If the session requested is not valid, it is not returned through the getSession() method.

 

isRequestedSessionIdFromCookie()

 

Returns true if the request's session ID provided by the client is a cookie, or false otherwise.

 

isRequestedSessionIdFromURL()

 

Returns true if the request's session ID provided by the client is a part of a URL, or false otherwise.

 

For example:

if ( request.isRequestedSessionIdValid() ) {
   if ( request.isRequestedSessionIdFromCookie() ) {
      // this session is maintained in a session cookie
   }
   // any other tasks that require a valid session
} else {
   // log an application error
}

Binding Data to a Session

You can bind objects to sessions in order to make them available across multiple user interactions.

The following table shows the HttpSession methods that provide support for binding objects to the session object. The left column lists HttpSession methods, and the right column lists descriptions of these methods.

   HttpSession Methods  

HttpSession Methods

Description

getAttribute()

 

Returns the object bound to a given name in the session or null if there is no such binding.

 

getAttributeNames()

 

Returns an array of names of all attributes bound to the session.

 

setAttribute()

 

Binds the specified object into the session with the given name. Any existing binding with the same name is overwritten. For an object bound into the session to be distributed it must implement the serializable interface.

 

removeAttribute()

 

Unbinds an object in the session with the given name. If there is no object bound to the given name this method does nothing.

 

Binding Notification with HttpSessionBindingListener

Some objects require you to know when they are placed in or removed from, a session. To obtain this information, implement the HttpSessionBindingListener interface in those objects. When your application stores or removes data with the session, the servlet engine checks whether the object being bound or unbound implements HttpSessionBindingListener. If it does, the Sun ONE Application Server notifies the object under consideration, through the HttpSessionBindingListener interface, that it is being bound into or unbound from the session.

Invalidating a Session

Specify the session to invalidate itself automatically after being inactive for a defined time period. Alternatively, invalidate the session manually with the HttpSession method invalidate().



Tip

The session API does not provide an explicit session logout API, so any logout implementation must call the session.invalidate() API.



 

Invalidating a Session Manually

To invalidate a session manually, simply call the following method:

session.invalidate();

All objects bound to the session are removed.

Setting a Session Timeout

Session timeout is set using the sun-web.xml deployment descriptor file. For more information, see the session-properties element in "Assembling and Deploying Web Modules."

Session Managers

A session manager automatically creates new session objects whenever a new session starts. In some circumstances, clients do not join the session, for example, if the session manager uses cookies and the client does not accept cookies.

Sun ONE Application Server 7 gives you these session management options:

  • StandardManager, the default session manager
  • PersistentManager, a provided session manager that uses a persistent data store


  • Note

    The session manager interface is Unstable. An unstable interface may be experimental or transitional, and hence may change incompatibly, be removed, or be replaced by a more stable interface in the next release.



StandardManager

The StandardManager is the default session manager.

Enabling StandardManager

You may want to specify StandardManager explicitly to change its default parameters. To do so, edit the sun-web.xml file for the web application as in the following example.

<sun-web-app>
   ...
   <session-config>
      <session-manager>
         <manager-properties>
            <property name="reapIntervalSeconds" value="20" />
         </manager-properties>
      </session-manager>
      ...
   </session-config>
   ...
</sun-web-app>

For more information about the sun-web.xml file, see "Assembling and Deploying Web Modules."

Manager Properties for StandardManager

The following table describes manager-properties properties for the StandardManager session manager. The left column lists the property name, the middle column indicates the default value, and the right column describes what the property does.

   manager-properties properties

Property Name

Default Value

Description

reapIntervalSeconds

 

60

 

Specifies the number of seconds between checks for expired sessions.

Setting this value lower than the frequency at which session data changes is recommended. For example, this value should be as low as possible (1 second) for a hit counter servlet on a frequently accessed website, or you could lose the last few hits each time you restart the server.

 

maxSessions

 

-1

 

Specifies the maximum number of active sessions, or -1 (the default) for no limit.

 

sessionFilename

 

none; state is not preserved across restarts

 

Specifies the absolute or relative pathname of the file in which the session state is preserved between application restarts, if preserving the state is possible. A relative pathname is relative to the temporary directory for this web application.

 

PersistentManager

The PersistentManager is the other session manager provided with Sun ONE Application Server. For session persistence, PersistentManager can use a file, to which each session is serialized. You can also create your own persistence mechanism.

Enabling PersistentManager

You may want to specify PersistentManager explicitly to change its default parameters. To do so, edit the sun-web.xml file for the web application as in the following example. Note that persistence-type must be set to file.

<sun-web-app>
   ...
   <session-config>
      <session-manager persistence-type=file>
         <manager-properties>
            <property name=reapIntervalSeconds value=20 />
         </manager-properties>
         <store-properties>
            <property name=directory value=sessions />
         </store-properties>
      </session-manager>
      ...
   </session-config>
   ...
</sun-web-app>

For more information about the sun-web.xml file, see "Assembling and Deploying Web Modules."

Manager Properties for PersistentManager

The following table describes manager-properties properties for the PersistentManager session manager. The left column lists the property name, the middle column indicates the default value, and the right column describes what the property does.

   manager-properties properties

Property Name

Default Value

Description

reapIntervalSeconds

 

60

 

Specifies the number of seconds between checks for expired sessions.

Setting this value lower than the frequency at which session data changes is recommended. For example, this value should be as low as possible (1 second) for a hit counter servlet on a frequently accessed website, or you could lose the last few hits each time you restart the server.

 

maxSessions

 

-1

 

Specifies the maximum number of active sessions, or -1 (the default) for no limit.

 

Store Properties for PersistentManager

The following table describes store-properties properties for the PersistentManager session manager. The left column lists the property name, the middle column indicates the default value, and the right column describes what the property does.

   store-properties properties

Property Name

Default Value

Description

reapIntervalSeconds

 

60

 

Specifies the number of seconds between checks for expired sessions for those sessions that are currently swapped out.

Setting this value lower than the frequency at which session data changes is recommended. For example, this value should be as low as possible (1 second) for a hit counter servlet on a frequently accessed website, or you could lose the last few hits each time you restart the server.

 

directory

 

directory specified by javax.servlet.context.tempdir context attribute

 

Specifies the absolute or relative pathname of the directory into which individual session files are written. A relative path is relative to the temporary work directory for this web application.

 


Previous      Contents      Index      Next     
Copyright 2003 Sun Microsystems, Inc. All rights reserved.