Previous     Contents     Index     DocHome     Next     
iPlanet Application Server Programmer's Guide (Java)



Chapter 11   Creating and Managing User Sessions


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

This chapter 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 EJBs 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 that 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.

iAS supports the servlet standard session interface HttpSession for all session activities. This interface enables you to write portable, secure servlets.

Additionally, iAS provides an additional interface HttpSession2, which gives support for a servlet security framework as well as sharing sessions between servlets and older iAS components (AppLogics).

Behind the scenes, there are two session styles, distributable sessions and local sessions. The main difference between them is that distributable sessions, as the name implies, can be distributed among multiple servers in a cluster, while local sessions are sticky (i.e., bound to an individual server). Sticky load balancing is automatically set for servlets of an application that is configured to use the local session model. You determine which session style to use in the application configuration file.


Sessions and Cookies

A cookie is a small collection of information that can be transmitted to a calling browser, and then retrieved on each subsequent call from that browser so that the server can recognize calls from the same client. The cookie is returned with each subsequent 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 URLs such that the session ID appears in URLs from that client.


Sessions and Security

The iAS security model is based on an authenticated user session. Once a session has been created, the application user can be authenticated and "logged in" to the session. Each step of an interaction, from the servlet that receives the request to the EJB that generates content to the JSP that formats the output, can be aware that the user has been properly authenticated.

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

For more information about security, see Chapter 12 "Writing Secure Applications".



How to Use Sessions



To use a session, you first create a session using the HttpServletRequest method getSession(). Once the session is established, you can examine and set its properties using the provided methods. You can set a session to time out after being inactive for a certain time, or you can invalidate it manually.

You can also bind objects to the session, thus storing 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 in the following example:

HttpSession mySession = request.getSession();

getSession() returns the valid session object associated with this request, identified in the session cookie which is encapsulated in the request object. If you call this method with no arguments, a session is created if there is not already a session associated with the request. If you call this method with a Boolean argument, then the session is created only if the argument is true.

This example shows the doPost() method from a servlet that 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

    }
}

For more information about getSession(), see the servlet specification.


Examining Session Properties

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

Use the following methods to examine properties in the session:


Table 11-1 HttpSession Methods

HttpSession method

Description

getCreationTime()  

Returns the time at which this session was created in milliseconds since January 1, 1970, 00:00:00 GMT.  

getId()  

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

getLastAccessedTime()  

Returns the last time the client sent a request carrying the identifier assigned to the session, or -1 if the session is new. Time is expressed as milliseconds since January 1, 1970, 00:00:00 GMT.  

isNew()  

Returns a Boolean value indicating whether this session is considered to be new. A session is considered to be new if it has been created by the server and not received from the client as part of this request. This means that the client has not "acknowledged" or "joined" the session and may not ever return the appropriate session identification information when it makes its next request.  

For example:

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

Use the following methods to inspect properties in the request object that relate to the session:


Table 11-2 HttpServletRequest Methods

HttpServletRequest method

Description

getRemoteUser()  

Gets the name of the user making this request. This information may be provided by HTTP authentication. Returns null if there is no user name information in the request.  

getRequestedSessionId()  

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

isRequestedSessionIdValid()  

Checks whether this request is associated with a session that is currently valid. If the session used by the request is not valid, it is not returned via the getSession() method.  

isRequestedSessionIdFromCookie()  

Returns true if the session ID for this request was provided from the client as a cookie, or false otherwise.  

isRequestedSessionIdFromURL()  

Returns true if the session ID for this request was provided from the client as 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 persistent across multiple user interactions. The following HttpSession methods provide support for binding objects to the session object:


Table 11-3 HttpSession Methods

HttpSession method

Description

getValue()  

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

getValueNames()  

Returns an array of the names of all the values bound into this session.  

putValue()  

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. Note that iAS RowSets and JDBC ResultSets are not serializable, and can not be distributed.  

removeValue()  

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 may require that you know when they are placed into, or removed from, a session. You can obtain this information by implementing the HttpSessionBindingListener interface in those objects. When your application stores data in or removes data from the session, the servlet engine checks whether the object being bound or unbound implements HttpSessionBindingListener. If it does, methods in the interface automatically notify the object that it has been bound or unbound.


Invalidating a Session

You can specify that the session invalidates itself automatically after being inactive for a certain amount of time. Alternatively, you can invalidate a session manually with the HttpSession method invalidate().

Note: The session API does not provide an explicit API for logging out from a session, so any implementation of a "Logout" 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 also removed.


Setting a Session Timeout
Session timeout is set using the ias-specific Deployment Descriptor. Refer to the session-info element in the section "Packaging for Deployment"


Controlling the Type of Session

You can control the type of session by setting the appropriate elements in the iAS-specific XML. Refer to the element session-info in Chapter 10 "Packaging for Deployment".


Sharing Sessions with AppLogics

Servlet programmers can use the iAS feature interface HttpSession2 to share distributable sessions between AppLogics and servlets. Sharing sessions is useful when you want to migrate an application from NAS 2.x to iAS. HttpSession2 interface adds security and direct manipulation of distributable sessions.

Additionally, if you establish a session in an AppLogic using loginSession() and you want to be able to access that session from a servlet, you must call the method setSessionVisibility() in the AppLogic class in order to instruct the session cookie to be transmitted to servlets as well as AppLogics. It is important to do this before calling saveSession().

For example, in an AppLogic:

domain=".mydomain.com";
path="/"; //make entire domain visible
isSecure=true;
if ( setSessionVisibility(domain, path, isSecure) == GXE.SUCCESS )
    { // session is now visible to entire domain }

For more information about setSessionVisibility(), see the entry for the AppLogic class in the Foundation Class Reference. For more information about sharing sessions between AppLogics and servlets, see the Migration Guide.


Previous     Contents     Index     DocHome     Next     
Copyright © 2000 Sun Microsystems, Inc. Some preexisting portions Copyright © 2000 Netscape Communications Corp. All rights reserved.

Last Updated June 25, 2000